Removing Whitespace from a String

What's the most efficient way to remove all whitespace from a std::string?

Removing all whitespace from a std::string is a common task in string processing, especially when cleaning up user input or formatting data. Here's an efficient way to accomplish this using the standard library:

#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>

std::string remove_whitespace(std::string str) {
  str.erase(std::remove_if(
    str.begin(), str.end(),
    [](unsigned char c) {
      return std::isspace(c);
    }),
    str.end()
  );
  return str;
}

int main() {
  std::string text{"  Hello,   World!  \t\n"};

  std::cout << "Original: '" << text << "'\n";
  std::cout << "Without whitespace: '"
            << remove_whitespace(text) << "'\n";
}
Original: '  Hello,   World!
'
Without whitespace: 'Hello,World!'

Let's break down the remove_whitespace() function:

  1. We use std::remove_if() to move all non-whitespace characters to the front of the string.
  2. The lambda function [](unsigned char c) { return std::isspace(c); } checks if a character is whitespace.
  3. std::isspace() from <cctype> checks for any whitespace character (space, tab, newline, etc.).
  4. str.erase() then removes all the whitespace characters that were moved to the end of the string.

This approach is known as the erase-remove idiom and is very efficient because it only traverses the string once and minimizes memory allocations.

If you want to modify the string in-place instead of returning a new string, you can do:

void remove_whitespace(std::string& str) {
  str.erase(std::remove_if(
    str.begin(), str.end(),
    [](unsigned char c) {
      return std::isspace(c);
    }),
    str.end()
  );
}

For even more efficiency, especially with longer strings, you can use std::string::reserve() to avoid reallocations:

std::string remove_whitespace(
  const std::string& str
) {
  std::string result;

  // Pre-allocate space
  result.reserve(str.length());

  for (char c : str) {
    if (!std::isspace(
      static_cast<unsigned char>(c)
    )) {
      result += c;
    }
  }

  return result;
}

This method might be slightly faster for very long strings as it avoids moving characters around, but it does create a new string. Choose the method that best fits your specific use case and performance needs.

A Deeper Look at the std::string Class

A detailed guide to std::string, covering the most essential methods and operators

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Efficient String Concatenation in Loops
How can I efficiently concatenate multiple strings in a loop without excessive memory allocation?
Converting String Case in C++
What's the best way to convert all characters in a std::string to uppercase or lowercase?
Splitting a String into a Vector
How can I split a std::string into a vector of substrings based on a delimiter?
Case-Insensitive String Comparison
How can I implement a case-insensitive string comparison using std::string?
Replacing All Substrings in a String
What's the best approach to replace all occurrences of a substring within a std::string?
Reversing a String in C++
What's the most efficient way to reverse a std::string?
Validating Email Addresses with Regex
How can I check if a std::string is a valid email address using regular expressions?
Checking if a String is a Palindrome
How can I efficiently check if a std::string is a palindrome?
Implementing Basic Autocomplete
How can I implement a basic autocomplete feature using a list of std::strings?
Calculating Levenshtein Distance
How can I efficiently calculate the Levenshtein distance between two std::strings?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant