Remove certain characters from a string in C++
This post will discuss how to remove certain characters from a string in C++.
1. Using std::remove function
The recommended approach is to use the std::remove algorithm that takes iterators at the beginning and end of the container and the value to be removed.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <string> #include <algorithm> int main() { std::string s = "#Hello #World!!"; std::string chars = "#!"; for (char c: chars) { s.erase(std::remove(s.begin(), s.end(), c), s.end()); } std::cout << s; return 0; } |
Output:
Hello World
Notice that the Erase-remove idiom technique is used since the std::remove algorithm does not actually remove characters from the string and expects a call to the std::erase algorithm.
2. Using std::remove_if function
The above solution makes multiple calls to the std::remove algorithm, one for each given character. Another feasible solution is to use the std::remove_if algorithm that takes a predicate to do the filtering.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <string> #include <algorithm> int main() { std::string s = "#Hello #World!!"; std::string chars = "#!"; s.erase(remove_if(s.begin(), s.end(), [&chars](const char &c) { return chars.find(c) != std::string::npos; }), s.end()); std::cout << s; return 0; } |
Output:
Hello World
The above solution calls the string::find function for every character in the given string. Since each call to find() takes linear time, the efficient solution is to insert characters to be removed into a std::unordered_set and call unordered_set::find instead.
That’s all about removing certain characters from a 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 :)