Remove punctuation from string in C++
This post will discuss how to remove punctuation from a string in C++.
1. Using std::remove_if
A simple solution is to use the std::remove_if standard algorithm with string::erase member function. The std::remove_if algorithm has no access to the string container and can only isolate the punctuation characters in the string. It returns an iterator that indicates where the end should be, which can be deleted with the std::erase function.
|
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> #include <cctype> int main() { auto it = std::remove_if(str.begin(), str.end(), [](char const &c) { return std::ispunct(c); }); str.erase(it, str.end()); std::cout << str << std::endl; // stdstringc11 return 0; } |
The code can be shortened using the ispunct function from the global namespace. It can be accessed as ::ispunct:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <string> #include <algorithm> #include <cctype> int main() { auto it = std::remove_if(str.begin(), str.end(), ::ispunct); str.erase(it, str.end()); std::cout << str << std::endl; // stdstringc11 return 0; } |
The std::remove_if algorithm updates the string in-place. To get the result as a new string with punctuation removed, consider using the std::remove_copy_if algorithm:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <string> #include <algorithm> int main() { std::string result; std::remove_copy_if(str.begin(), str.end(), std::back_inserter(result), std::ptr_fun<int, int>(&std::ispunct)); std::cout << result << std::endl; // stdstringc11 return 0; } |
2. Using Reverse Loop
Alternatively, you can use a regular for loop to identify punctuations from the string and remove them using the string::erase function. We should loop in reverse order to avoid any non-deterministic behavior while removing elements while iterating.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <string> #include <cctype> int main() { for (int i = str.size() - 1; i >= 0; i--) { if (ispunct(str[i])) { str.erase(i, 1); } } std::cout << str << std::endl; // stdstringc11 return 0; } |
That’s all about removing punctuation 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 :)