这是我在字符串中查找序列并将其替换为另一个序列的代码:
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;
}
我希望这可以帮助一些遇到同样问题的人。