We are committed to provide service 24 X 7

Deals, Shopping, Training, Tools

Find and Replace all occurrences of a sub string in C++

In this article we will discuss how to replace all occurrences of a sub string with new string in C++.


For example, we have a string i.e.

Advertisements

“Boost Library is simple C++ Library”

And we want replace all occurrences of ‘Lib’ with XXX. Let’s see the different methods to do it,

Find & Replace all sub strings – using STL

#include <iostream>
#include <string>

void findAndReplaceAll(std::string & data, std::string toSearch, std::string replaceStr)
{
	// Get the first occurrence
	size_t pos = data.find(toSearch);

	// Repeat till end is reached
	while( pos != std::string::npos)
	{
		// Replace this occurrence of Sub String
		data.replace(pos, toSearch.size(), replaceStr);
		// Get the next occurrence from the current position
		pos =data.find(toSearch, pos + replaceStr.size());
	}
}

int main()
{
	std::string data = "Boost Library is simple C++ Library";

	std::cout<<data<<std::endl;

	findAndReplaceAll(data, "Lib", "XXX");

	std::cout<<data<<std::endl;


	return 0;
}

Output:

Boost Library is simple C++ Library
Boost XXXrary is simple C++ XXXrary

Find & Replace all sub strings – using Boost::replace_all

#include <iostream>
#include <string>
#include <boost/algorithm/string.hpp>



int main()
{
	std::string data = "Boost Library is simple C++ Library";

	std::cout<<data<<std::endl;

	// Replace all occurrences of 'LIB' with 'XXX'
	// Case Sensitive Version
	boost::replace_all(data, "Lib", "XXX");

	std::cout<<data<<std::endl;


}

Output:

Boost Library is simple C++ Library
Boost XXXrary is simple C++ XXXrary

Find & Replace all Case Insensitive Sub Strings using Boost::ireplace_all

#include <iostream>
#include <string>
#include <boost/algorithm/string.hpp>



int main()
{
	std::string data = "Boost Library is simple C++ Library";

	std::cout<<data<<std::endl;

	// Replace all occurrences of 'LIB' with 'XXX'
	// Case Insensitive Version
	boost::ireplace_all(data, "LIB", "XXX");

	std::cout<<data<<std::endl;


}

Output:

Boost Library is simple C++ Library
Boost XXXrary is simple C++ XXXrary

 

Cart

Your Cart is Empty

Back To Shop