Trim Whitespace

How can I trim whitespace from the beginning and end of a std::string?

Trimming whitespace from the beginning and end of a std::string is a common task in text processing. Here are several ways to achieve this in C++.

Using Custom Functions

For example:

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

std::string TrimWhitespace(const std::string& str) {
  size_t first = str.find_first_not_of(' ');
  size_t last = str.find_last_not_of(' ');
  return str.substr(first, (last - first + 1));
}

int main() {
  std::string Text{"   Hello, World!   "};

  std::string Trimmed = TrimWhitespace(Text);  

  std::cout << '"' << Trimmed << '"';
}
"Hello, World!"

Using std::isspace

You can also use std::isspace to handle all types of whitespace characters. For example:

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

std::string TrimWhitespace(const std::string& str) {
  auto start = std::find_if_not(
    str.begin(), str.end(), ::isspace
  );  

  auto end = std::find_if_not(
    str.rbegin(), str.rend(), ::isspace
  ).base();  

  return (start < end) ? std::string(start, end)
                       : std::string();
}

int main() {
  std::string Text{"\t  Hello, World! \n"};
  std::string Trimmed = TrimWhitespace(Text);  
  std::cout << '"' << Trimmed << '"';
}
"Hello, World!"

Using Regular Expressions

If you prefer using regular expressions, you can use the <regex> library to trim whitespace. For example:

#include <iostream>
#include <string>
#include <regex>

std::string TrimWhitespace(const std::string& str) {
  std::regex wsRegex("^\\s+|\\s+$");
  return std::regex_replace(str, wsRegex, "");  
}

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

  std::string Trimmed = TrimWhitespace(Text);  

  std::cout << '"' << Trimmed << '"';
}
"Hello, World!"

Considerations

  • Efficiency: Custom functions are generally more efficient for simple whitespace trimming.
  • Flexibility: Using std::isspace ensures all whitespace characters are handled.
  • Complexity: Regular expressions can handle more complex patterns but may be slower.

By using these methods, you can effectively trim whitespace from the beginning and end of a std::string.

Manipulating std::string Objects

A practical guide covering the most useful methods and operators for working with std::string objects and their memory

Questions & Answers

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

Concatenate Strings in C++
How can I concatenate two std::string objects in C++?
The append() Method vs += Operator
What is the difference between append() and += operator for strings in C++?
Insert Substring in C++
How can I insert a substring into a specific position within a std::string?
Replace Substring in C++
How can I replace a substring within a std::string with another string?
Iterate over String
How can I iterate through each character of a std::string using a range-based for loop?
Reserve vs Resize
What is the difference between reserve() and resize() methods in std::string?
Convert to wstring
How can I convert a std::string to a std::wstring?
Count Character Occurrences
How can I count the number of occurrences of a character in a std::string?
Restrict String Length
How can I ensure a std::string does not exceed a specific length?
Reverse String
How can I reverse the contents of a std::string?
Compare String vs Vector
What are the differences between std::string and std::vector?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant