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.

Download  Run Code

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.

Download  Run Code

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++.