这是我在字符串中查找序列并将其替换为另一个序列的代码:
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;
}
我希望这能帮助一些遇到同样问题的人。
最佳答案
你有一个无限循环,因为你的条件没有向前发展。您始终在运行 j = source.find( find )
,但您将 '
替换为 ''
,因此您始终每次都找到第一个撇号并在字符串中添加一个新的撇号。
您需要通过在每次替换内容时向前移动您正在扫描的位置来确保您不会两次匹配同一个撇号。
find
函数采用第二个参数,它是字符串中查找子字符串的起始位置。找到第一个匹配项的位置后,将起始位置向上移动到该位置加上要替换的字符串的长度。
关于c++ - C++ 查找和替换函数的单引号问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1087088/