/ Published in: C++
example: findandreplace( source, "\n", "\n" );
Expand |
Embed | Plain Text
void find_and_replace( string &source, const string find, string replace ) { size_t j; for ( ; (j = source.find( find )) != string::npos ; ) { source.replace( j, find.length(), replace ); } }
Comments
Subscribe to comments
You need to login to post a comment.

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