This post will discuss how to replace consecutive whitespace with a single space in a string in C++.

1. Using std::unique

The std::unique function is used to remove consecutive duplicates in the specified range. It takes a binary predicate to determine whether specified arguments are equivalent or not. It can be used as follows to remove all duplicate whitespaces.

Download  Run Code

 
The above code can be easily shortened using lambda expressions:

Download  Run Code

 
To create a copy of the string with duplicates removed, consider using the std::unique_copy algorithm:

Download  Run Code

2. Using Regex

Another option is to use a regular expression to replace consecutive whitespace with a single space. Starting with C++11, we can use std::regex_replace from the header <regex>. Its usage is demonstrated below:

Download  Run Code

 
Alternatively, we can use the boost::regex_replace algorithm by boost library. Here’s an example of its usage:

Download Code

3. Using std::istringstream

Finally, we can use std::istringstream to remove duplicate whitespace in a string. Here’s an example of its usage, which removes trailing and leading spaces as well:

Download  Run Code

That’s all about replacing consecutive whitespace with a single space in a string in C++.