This post will discuss how to replace all occurrences of a substring in a string in C++.

1. Using string::find

There is no built-in function to replace all occurrences of a substring in a string in C++. To find all instances of a substring in a string, we can call the string::find function, and replace each occurrence with the string::erase and string::insert functions. For example,

Download  Run Code

 
The call to the string::erase and string::insert function can be replaced with a single call to the string::replace function, as shown below:

Download  Run Code

2. Using Boost

If you’re using the boost string algorithm library in your project, you can use the boost::replace_all algorithm from the <boost/algorithm/string/replace.hpp> header. The following C++ program demonstrates its usage:

Download Code

 
To avoid any modification on the original string, consider using the boost::replace_all algorithm.

Download Code

3. Using std::regex_replace

Starting with C++11, we can use the std::regex_replace function for this. Its usage is demonstrated below:

Download  Run Code

That’s all about replacing all occurrences of a substring in a string in C++.