Skip to content
Blog C++/CPP: Search and Replace in String

C++/CPP: Search and Replace in String

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!

1 thought on “C++/CPP: Search and Replace in String”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.