单引号问题与C++查找和替换功能

Cor*_*ker 1 c++ quotes replace

这是我在字符串中查找序列并将其替换为另一个序列的代码:

std::string find_and_replace( string &source, string find, string replace )
{
    size_t j;
    for ( ; (j = source.find( find )) != string::npos ; )
    {
        source.replace( j, find.length(), replace );
    }
    return source;
}
Run Code Online (Sandbox Code Playgroud)

当我打电话时,一切正常:

find_and_replace(test, "foo", "bar")
Run Code Online (Sandbox Code Playgroud)

我的申请要求我用两个单引号替换单引号,而不是双引号.比如我打电话:

find_and_replace(test, "'", "''")
Run Code Online (Sandbox Code Playgroud)

但每当我打电话给这个时,函数就会因某种原因冻结.有谁知道这个问题可能是什么原因?

编辑:基于我得到的答案,我修复了代码:

std::string find_and_replace( string &source, string find, string replace )
{
    string::size_type pos = 0;
    while ( (pos = source.find(find, pos)) != string::npos ) {
        source.replace( pos, find.size(), replace );
        pos += replace.size();
    }
    return source;
}
Run Code Online (Sandbox Code Playgroud)

我希望这有助于一些人遇到同样的问题.

Wel*_*bog 10

你有一个无限循环,因为你的状况不会向前发展.你总是在运行 j = source.find( find ),但您要更换''',所以你总是在发现第撇号每次和添加新的撇号的字符串.

每次更换东西时,你需要确保两次相同的撇号都不匹配.

find函数接受第二个参数,该参数是字符串中的起始位置以查找子字符串.找到第一场比赛的位置后,将起始位置移动到该位置加上您要替换它的弦长.