Skip to content

Instantly share code, notes, and snippets.

@serge1
Created May 7, 2013 10:08
Show Gist options
  • Save serge1/5531600 to your computer and use it in GitHub Desktop.
Save serge1/5531600 to your computer and use it in GitHub Desktop.
C++ STL implementation of string search and replace
void
search_and_replace( std::string& value, std::string const& search,
std::string const& replace )
{
std::string::size_type next;
for ( next = value.find( search ); // Try and find the first match
next != std::string::npos; // next is npos if nothing was found
next = value.find( search, next ) // search for the next match starting after
// the last match that was found.
) {
// Inside the loop. So we found a match.
if ( next == 0 || value[next - 1] != '\r' ) {
value.replace( next, search.length(), replace ); // Do the replacement.
}
// Move to just after the replace. This is the point were we start
// the next search from.
next += replace.length();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment