My CPP function for search and replace in string is given below:
string search_replace( string String, string searchString,
string replaceString, string::size_type pos = 0) {
while ( (pos = String.find(searchString, pos)) != string::npos ) {
String.replace( pos, searchString.size(), replaceString );
pos += replaceString.size();
}
return String;
}
Sample program using it.
/*
* searchreplace.cpp
*
* Copyright 2010 Dipin Krishna [email protected]
* Licensed under GPL Version 3
*
* To compile - g++ -o searchreplace searchreplace.cpp
* To execute - ./searchreplace
*/
#include <iostream>
#include <string>
using namespace std;
string search_replace( string String, string searchString,
string replaceString, string::size_type pos = 0) {
while ( (pos = String.find(searchString, pos)) != string::npos ) {
String.replace( pos, searchString.size(), replaceString );
pos += replaceString.size();
}
return String;
}
int main() {
string str1( "I love coding in C and CPP and PHP and PERL" );
cout << str1 << endl;
cout << search_replace( str1, "and", "&" ) << endl;
cout << search_replace( str1, "and", "&", 26 ) << endl;
}
Expected Output
I love coding in C and CPP and PHP and PERL
I love coding in C & CPP & PHP & PERL
I love coding in C and CPP & PHP & PERL
Enjoy Coding!
Beautiful code! Please specify namespace – ‘using namespace std;’