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