题
下面是我在一个字符串发现的序列,并用另一个替换它的代码:
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
函数采用其是字符串中的起始位置来寻找子串的第二参数。一旦你找到的第一个匹配的位置,移动起始位置到这一位置以及你与替换它的字符串的长度。
其他提示
由于你“与'替换,然后搜索”一遍,发现您第一次只是把那里的人的。您更换。等。
您试图取代您添加相同的字符串。
有可能更好地从右到左的工作。这对我的作品:
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;
}
不隶属于 StackOverflow