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

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 it as if, but becoming an endless loop. Why?

+3


source share


2 answers


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

      

+3


source


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

This should also have the best worst complexity, as code using string replacement might 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 a simple example, but as you can see, the number of copies can increase quadratically.

You can also avoid this by creating the result string in one pass instead of using string :: replace.

0


source







All Articles