使用c++将字符串中的单引号替换为两个单引号

Replace single quote with two single quotes in a string using c++

本文关键字:单引号 两个 替换 字符串 使用 c++      更新时间:2023-10-16

下面的函数正在按预期工作。但我认为我可以用一种有效的方式来做。

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

James Kanze的回答很好。不过,为了好玩,我会提供一个更像C++11的版本。
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;
}

例如,可能值得一试。但前提是你找到了原件版本成为代码的瓶颈;没有意义比必要的更复杂的事情。