3
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.
}

Want to replace tho as though, but becoming an infinite loop. Why?

XIAODI
  • 109
  • 5
  • 1
    possible duplicate of [How to find and replace string?](http://stackoverflow.com/questions/5878775/how-to-find-and-replace-string) – ZivS Apr 27 '15 at 07:03
  • 1
    You get infinite loop because the replace string contains the search pattern. I.e.: `"tho" -> "though" -> "thothough" -> ...` – bolov Apr 27 '15 at 07:06

2 Answers2

3

Try like this:

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;
}
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0

In C++11 (or using Boost), you could use regex_replace: http://www.cplusplus.com/reference/regex/regex_replace/

This should also have better worst case complexity as the code using string replace may need to copy a lot of data, e.g.:

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

= 42 characters copied in total to create a 24 character string. Not so bad in the simple example but as you can see the number of copies may grow quadratically.

You could also avoid this by creating the result string in a single pass instead of using string::replace.

Arne Vogel
  • 6,346
  • 2
  • 18
  • 31