Posted By

yuconner on 09/11/06


Tagged

String


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

copyleft
oakdragon
khouser


Find and replace one string with another


 / Published in: C++
 

example: findandreplace( source, "\n", "\n" );

  1. void find_and_replace( string &source, const string find, string replace ) {
  2.  
  3. size_t j;
  4. for ( ; (j = source.find( find )) != string::npos ; ) {
  5. source.replace( j, find.length(), replace );
  6. }
  7. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: icstatic on November 26, 2009

There are two bugs in this snippet, both result in an infinite loop.

If you run this function with a replace string that contains the find string it will infinitely expand the input string. Likewise if you run the function with a zero length find string it will also infinitely expand.

This version fixes this problem:

void FindAndReplace( std::string& tInput, std::string tFind, std::string tReplace ) { sizet uPos = 0; sizet uFindLen = tFind.length(); size_t uReplaceLen = tReplace.length();

if( uFindLen == 0 )
{
    return tInput;
}

for( ;(uPos = tInput.find( tFind, uPos )) != std::string::npos; )
{
    tInput.replace( uPos, uFindLen, tReplace );
    uPos += uReplaceLen;
}

}

You need to login to post a comment.