1

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

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;
}

当我调用类似以下内容时,一切正常:

find_and_replace(test, "foo", "bar")

我的应用程序要求我用两个单引号代替一个单引号,而不是一个双引号。例如我会打电话:

find_and_replace(test, "'", "''")

但是每当我调用它时,该函数都会由于某种原因冻结。有谁知道这个问题的原因可能是什么?

编辑:根据我得到的答案,我已经修复了代码:

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;
}

我希望这可以帮助一些遇到同样问题的人。

4

4 回答 4

10

你有一个无限循环,因为你的条件没有前进。你总是在运行 j = source.find( find ),但你用 替换'''所以你总是每次都找到第一个撇号并在字符串中添加一个新的撇号。

每次替换某些东西时,您需要通过向前扫描的位置移动来确保不会两次匹配同一个撇号。

find函数采用第二个参数,它是字符串中查找子字符串的起始位置。找到第一个匹配的位置后,将起始位置向上移动到该位置加上要替换它的字符串的长度。

于 2009-07-06T13:53:05.730 回答
4

因为您将 ' 替换为 '',然后再次搜索 ',找到您刚刚放在那里的第一个。你替换哪个。等等。

于 2009-07-06T13:52:09.850 回答
1

您正在尝试替换您添加的相同字符串。

于 2009-07-06T13:53:22.877 回答
1

从右到左工作可能会更好。这对我有用:

const std::string& replacestring( std::string& strString, const std::string& strOld, const std::string& strNew )
{
    for ( int nReplace = strString.rfind( strOld ); nReplace != std::string::npos; nReplace = strString.rfind( strOld, nReplace - 1 ) )
    {
        strString.replace( nReplace, strOld.length(), strNew );
        if ( nReplace == 0 )
            break;
    }
    return strString;
}
于 2009-07-06T13:55:35.977 回答