Trim Whitespace in C++ Without Regex (Left, Right, Both)
Trim Whitespace in C++ Without Regex (Left, Right, Both)
Effortlessly remove leading and/or trailing whitespace from strings using simple functions in C++.
Trimming whitespace is a common task when processing user input or cleaning up data. While regular expressions can be used, they are often overkill for this simple operation. In this guide, we will walk through creating functions in C++ to trim whitespace from the left, right, or both ends of a string without using regex.Left Trim
Hereās how you can create a function to trim leading whitespace:
#include <iostream>
#include <string>
std::string leftTrim(const std::string& str) {
size_t start = str.find_first_not_of(" \t\n\r\f\v");
return (start == std::string::npos) ? "" : str.substr(start);
}
Right Trim
Similarly, hereās a function to trim trailing whitespace:
std::string rightTrim(const std::string& str) {
size_t end = str.find_last_not_of(" \t\n\r\f\v");
return (end == std::string::npos) ? "" : str.substr(0, end + 1);
}
Both Trim
To trim both leading and trailing whitespace, you can combine the two functions:
std::string trim(const std::string& str) {
return leftTrim(rightTrim(str));
}
Usage Example
Hereās how you can use these functions:
int main() {
std::string input = " Hello, World! ";
std::cout << "Original: '" << input << "'" << std::endl;
std::string leftTrimmed = leftTrim(input);
std::cout << "Left Trimmed: '" << leftTrimmed << "'" << std::endl;
std::string rightTrimmed = rightTrim(input);
std::cout << "Right Trimmed: '" << rightTrimmed << "'" << std::endl;
std::string bothTrimmed = trim(input);
std::cout << "Both Trimmed: '" << bothTrimmed << "'" << std::endl;
return 0;
}
Conclusion
Efficiently trimming whitespace from strings in C++ can be easily accomplished without the need for complex regular expressions. By using these simple functions, you can handle left, right, or both types of trimming as needed, making your code cleaner and more efficient. This approach ensures that your string manipulations are straightforward and performant.