This post will discuss how to remove whitespace from a string in C++.

By default, the following characters are considered whitespace characters:

  1. space ' '
  2. line feed '\n'
  3. carriage return '\r'
  4. horizontal tab '\t'
  5. form feed '\f'
  6. vertical tab '\v'

1. Using std::remove_if function

The standard solution is to use the std::remove_if algorithm to remove whitespace characters from std::string using the Erase-remove idiom technique. Since the std::remove_if algorithm does not actually remove characters from the string but move all non-whitespace characters to the front and returns an iterator pointing to where the end should be. We can then delete the whitespace characters with a call to std::erase.

 
std::remove_if expects a predicate that determines which characters to remove from the string. There are many ways to specify the predicate that removes whitespace characters:

::isspace

We can use isspace() defined in the cctype header, which checks for whitespace characters classified by the currently installed C locale.

Download  Run Code

Output:

HelloWorld

std::isspace

Instead of relying on the whitespace characters classified by the C locale, we can use std::isspace defined in header locale, which classify the whitespace character with the specified locale’s ctype facet.

Download  Run Code

 
With C++11, we can use lambdas instead of std::bind:

Download  Run Code

⮚ Custom predicate

Instead of using ::isspace or std::isspace, we can even write a custom predicate that returns true if the character is classified as a whitespace character and false otherwise. There are many ways to achieve that in C++:

⮚1. Unary Function

Download  Run Code

⮚2. Object of a class implementing () operator

Download  Run Code

⮚3. Lambda

Download  Run Code

2. Using std::regex_replace function

With C++11, we can also use std::regex_replace for this. This is demonstrated below:

Download  Run Code

3. Using Boost Library

Finally, we can go with boost::algorithm::erase_all, which removes all the occurrences of the space string from the input.

Download Code

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