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.

Download  Run Code

 
The code can be shortened using the ispunct function from the global namespace. It can be accessed as ::ispunct:

Download  Run Code

 
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:

Download  Run Code

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.

Download  Run Code

That’s all about removing punctuation from a string in C++.