以下功能正常运行。但我想我能以有效的方式做到这一点。
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;
}
答案 0 :(得分:3)
boost::replace_all(str, "'", "''");
http://www.boost.org/doc/libs/1_49_0/doc/html/boost/algorithm/replace_all.html
答案 1 :(得分:1)
也许使用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();
}
答案 2 :(得分:1)
可能性(将修改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;
}
答案 3 :(得分:1)
显而易见的解决方案是:
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;
}
例如,可能值得一试。但只有你找到原件 版本是代码中的瓶颈;制作没有意义 更复杂的事情。
答案 4 :(得分:0)
詹姆斯坎泽的答案很好。尽管如此,我还是会提供一个更加C ++ 11的人。
string DoubleQuotes(string value)
{
string retval;
for (auto ch : value)
{
if (ch == '\'')
{
retval.push_back('\'');
}
retval.push_back(ch);
}
return retval;
}