2009-07-06 90 views
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; 
} 

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

+0

嗯,任何原因downvote?没有正当理由的下降是无用的,因为他们不告诉创作者如何改进他们的问题。 – 2009-07-06 16:04:54

回答

9

你有一个无限循环,因为你的情况不会前进。你总是运行j = source.find(find),但是你用''代替',所以你总是每次都找到第一个撇号,并为该字符串添加一个新的撇号。

您需要确保在每次替换某些东西时移动要向前扫描的位置,以避免两次匹配相同的撇号。

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

4

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

1

您试图替换您添加的相同字符串。

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

从右到左没有区别,除非意外。 – 2009-07-06 14:12:45