C++将<单词 A>替换为<单词包含 A>

C++ replace a <word A> with a <word contains A>

本文关键字:gt lt 单词包 单词 C++ 替换      更新时间:2023-10-16
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.
}

想取代你,好像,但成为一个无限循环。为什么?

尝试如下:

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

在 C++11(或使用 Boost)中,您可以使用regex_replace: http://www.cplusplus.com/reference/regex/regex_replace/

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

thothothotho -> (copy 15 characters)
thoughthothotho -> (copy 12 characters)
thoughthoughthotho -> (copy 9 characters)
thoughthoughthoughtho -> (copy 6 characters)
thoughthoughthoughthough

= 总共复制 42 个字符以创建 24 个字符的字符串。在简单示例中还不错,但如您所见,副本数可能会二次增长。

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