How to Trim Whitespace

beginner c++11 strings

The C++ strings library does not include many common string functions such as trim whitespace. To implement trim we’ll use the methods find_first_not_of and find_last_not_of to find the first and last non-whitespace characters in a given string. We’ll then return the substring (substr) starting at the first non-whitespace character and ending at the last non-whitespace character, trimming the whitespace from the string. We’ll be careful to handle the case where the given string is all whitespace. Here’s an example trim whitespace function:

#include <string>
#include <iostream>

std::string trim(const std::string& s) {
  // Whitespace is one of: space, tab, carriage return,
  // line feed, form feed, or vertical tab.
  const char* whitespace = " \t\n\r\f\v";
  size_t begin = s.find_first_not_of(whitespace);
  if (begin == std::string::npos) {
    return std::string{};
  }
  size_t end = s.find_last_not_of(whitespace);
  return std::string{s.substr(begin, end - begin + 1)};
}

int main() {
  std::string jupiter{"   Jupiter   "}; 
  jupiter = trim(jupiter);
  std::cout << jupiter << "\n";

  std::cout << trim(" \t\n\r\f\v") << "\n";

  std::string mars = trim("\tMars    \n");
  std::cout << mars << "\n";
}
Jupiter

Mars


For more C++ By Example, click here.