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++.
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!"
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!"
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!"
std::isspace
ensures all whitespace characters are handled.By using these methods, you can effectively trim whitespace from the beginning and end of a std::string
.
Answers to questions are automatically generated and may not have been reviewed.
std::string
ObjectsA practical guide covering the most useful methods and operators for working with std::string
objects and their memory