使用c++将字符串中的单引号替换为两个单引号
Replace single quote with two single quotes in a string using c++
下面的函数正在按预期工作。但我认为我可以用一种有效的方式来做。
input = "Hello' Main's World";
函数返回值"Hello'Main'的世界";
string ReplaceSingleQuote(string input)
{
int len = input.length();
int i = 0, j =0;
char str[255];
sprintf(str, input.c_str());
char strNew[255];
for (i = 0; i <= len; i++)
{
if (str[i] == ''')
{
strNew[j] = ''';
strNew[j+ 1] = ''';
j = j + 2;
} else
{
strNew[j] = str[i];
j = j + 1 ;
}
}
return strNew;
}
boost::replace_all(str, "'", "''");
http://www.boost.org/doc/libs/1_49_0/doc/html/boost/algorithm/replace_all.html
string DoubleQuotes(string value)
{
string retval;
for (auto ch : value)
{
if (ch == ''')
{
retval.push_back(''');
}
retval.push_back(ch);
}
return retval;
}
也许使用std::stringstream
:
string ReplaceSingleQuote(string input)
{
stringstream s;
for (i = 0; i <= input.length(); i++)
{
s << input[i];
if ( input[i] == ''' )
s << ''';
}
return s.str();
}
一种可能性(将修改input
)是使用std::string::replace()
和std::string::find()
:
size_t pos = 0;
while (std::string::npos != (pos = input.find("'", pos)))
{
input.replace(pos, 1, "''", 2);
pos += 2;
}
显而易见的解决方案是:
std::string
replaceSingleQuote( std::string const& original )
{
std::string results;
for ( std::string::const_iterator current = original.begin();
current != original.end();
++ current ) {
if ( *current == ''' ) {
results.push_back( ''');
}
results.push_back( *current );
}
return results;
}
小的变化可能会提高性能:
std::string
replaceSingleQuote( std::string const& original )
{
std::string results(
original.size()
+ std::count( original.begin(), original.end(), '''),
''' );
std::string::iterator dest = results.begin();
for ( std::string::const_iterator current = original.begin();
current != original.end();
++ current ) {
if ( *current == ''' ) {
++ dest;
}
*dest = *current;
++ dest;
}
return results;
}
例如,可能值得一试。但前提是你找到了原件版本成为代码的瓶颈;没有意义比必要的更复杂的事情。
相关文章:
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- 如何返回一个类的两个对象相加的结果
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 两个字符串在 c++ 中不相等
- 按 Tab 单步执行两个控制组
- 宏定义中的预处理器令牌两边有两个双引号
- 在这种单例实施中,是否可以对两个商店重新排序?
- 如何使用C++中不是文字的变量在数字中显示单引号和两个引号?假设 6'2" 英尺
- 如何在FLTK中使用两个不同的小部件使用键盘箭头和鼠标单击
- 将两个单浮子存储在一个中
- 用鼠标打开不同的 Url,单击两个不同的图像C++
- 当我使用两个以上的双引号 (\) 时进程未启动
- 使用c++将字符串中的单引号替换为两个单引号
- 等待在QML界面中单击两个按钮
- 是否有可能在qt中的一个类中切换两个UI表单?
- 指向两个不同结构表的单指针
- 两个线程访问单例类 - 无法正常工作