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.

“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,

Advertisements

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

 

Do you want to Learn Modern C++ from best?

We have curated a list of Best C++ Courses, that will teach you the cutting edge Modern C++ from the absolute beginning to advanced level. It will also introduce to you the word of Smart Pointers, Move semantics, Rvalue, Lambda function, auto, Variadic template, range based for loops, Multi-threading and many other latest features of C++ i.e. from C++11 to C++20.

Check Detailed Reviews of Best Modern C++ Courses

Remember, C++ requires a lot of patience, persistence, and practice. So, start learning today.

2 thoughts on “Find and Replace all occurrences of a sub string in C++”

Leave a Comment

Your email address will not be published.

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

Scroll to Top