Replace all occurrences of a character in string in C++
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <string> int main() { std::string s = "C**"; std::string x = "*", y = "+"; size_t pos; while ((pos = s.find(x)) != std::string::npos) { s.replace(pos, 1, y); } std::cout << s; return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> #include <algorithm> #include <string> int main() { std::string s = "C**"; const char x = '*'; const char y = '+'; std::replace(s.begin(), s.end(), x, y); std::cout << s; return 0; } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#include <iostream> #include <string> #include <boost/algorithm/string/replace.hpp> int main() { std::string s = "C**"; std::string x = "*", y = "+"; boost::replace_all(s, x, y); std::cout << s; return 0; } |
Output:
C++
That’s all about replacing all occurrences of a character in string in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)