C++ C++;替换a<;单词A>;使用<;word包含一个>; void func(string&s,string const&oldVal,string const&newVal)//执行替换的函数 { while(s.find(oldVal)!=string::npos)//继续查找 s、 替换(s.find(oldVal)、newVal.size()、newVal); } int main()//主函数,测试用例 { 字符串s(“tho”); func(s,“tho”,“虽然”); 试着这样做: void func(string &s, string const& oldVal, string const& newVal) //function to do the replace { while(s.find(oldVal) != string::npos) //keep finding s.replace(s.find(oldVal), newVal.size(), newVal); } int main() //main function, test case { string s("tho"); func(s, "tho", "though"); cout << s << endl; // expected output: though. }

C++ C++;替换a<;单词A>;使用<;word包含一个>; void func(string&s,string const&oldVal,string const&newVal)//执行替换的函数 { while(s.find(oldVal)!=string::npos)//继续查找 s、 替换(s.find(oldVal)、newVal.size()、newVal); } int main()//主函数,测试用例 { 字符串s(“tho”); func(s,“tho”,“虽然”); 试着这样做: void func(string &s, string const& oldVal, string const& newVal) //function to do the replace { while(s.find(oldVal) != string::npos) //keep finding s.replace(s.find(oldVal), newVal.size(), newVal); } int main() //main function, test case { string s("tho"); func(s, "tho", "though"); cout << s << endl; // expected output: though. },c++,c++11,C++,C++11,在C++11(或使用Boost)中,可以使用regex_替换: 这也应该具有更好的最坏情况复杂性,因为使用字符串替换的代码可能需要复制大量数据,例如: std::string& func(string &s, string const& oldVal, string const& newVal) //function to do the replace { size_t pos = 0, fpos; while((fpos = s.find(ol

在C++11(或使用Boost)中,可以使用regex_替换:

这也应该具有更好的最坏情况复杂性,因为使用字符串替换的代码可能需要复制大量数据,例如:

std::string& func(string &s, string const& oldVal, string const& newVal) //function to do the replace 
{
    size_t pos = 0, fpos;
    while((fpos = s.find(oldVal, pos)) != string::npos) //keep finding 
    {
        s.replace(fpos, newVal.size(), newVal);
        pos = fpos + newVal.length();
    }
  return s;
}
=总共复制42个字符以创建一个24个字符的字符串。在简单的示例中,这并不糟糕,但正如您所看到的,副本的数量可能会以二次方的方式增长


您也可以通过在一次过程中创建结果字符串而不是使用string::replace来避免这种情况。

仍然处于无限循环中。@XIAODI:-请现在检查!谢谢,但我想知道有没有更简单的方法来做到这一点,也许这已经够简单了。.由于replace字符串包含搜索路径,您可能会得到无限循环例如:
“tho”->“thouth”->“thouth”->…
thothothotho -> (copy 15 characters)
thoughthothotho -> (copy 12 characters)
thoughthoughthotho -> (copy 9 characters)
thoughthoughthoughtho -> (copy 6 characters)
thoughthoughthoughthough