C++/CPP: Search and Replace in String

On October 16, 2010, in Coding, CPP, by Dipin Krishna

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 mail@dipinkrishna.com
* 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!

Tagged with:  

1 Response » to “C++/CPP: Search and Replace in String”

  1. Ershad K says:

    Beautiful code! Please specify namespace – ‘using namespace std;’

Leave a Reply

*

Search