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

1. Using std::string::replace function

The string class doesn’t provide any function to replace all occurrences of a character in a string with another character. The best you can do is repeatedly call std::string::replace until all matching characters are replaced with the help of std::string::find, as shown below:

Download  Run Code

Output:

C++

 
This solution is recommended only if the total number of characters to be replaced m are minimal compared to the length of the string n, i.e., m << n.

The worst-case time complexity of this approach is O(n2), where n is the length of the string. The worst-case happens when all characters in the string are the same as the specified character and the find() function executes n times. The best case O(n) happens when the input string doesn’t have a single occurrence of the given character.

2. Using std::replace function

The recommended solution is to use the standard algorithm std::replace from the <algorithm> header. It does one linear scan of the string and in-place replaces all the matching characters.

Download  Run Code

Output:

C++

3. Using Boost Library

If you’re using the boost in your project, you can go with the boost::replace_all algorithm, as shown below:

Download Code

Output:

C++

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