How to trim whitespace from beginning and end of std::string in C++?
Hello everyone! I'm a beginner C++ developer writing a simple program for processing user input. I need to remove extra whitespace (including tabs and newlines) from the beginning and end of a string. For example, the string " Hello, World! " should become "Hello, World!".
I know that C++ has std::string, but I can't find a built-in method for trimming. I tried writing my own function using loops, but the code turns out cumbersome and inconvenient.
Here's what I tried to do:
```cpp
std::string trim(std::string str) {
// Remove leading whitespace
while (str[0] == ' ') {
str.erase(0, 1);
}
// Remove trailing whitespace
while (str[str.size() - 1] == ' ') {
str.pop_back();
}
return str;
}
```
But this only works for s
No answers yet.
Log in to leave an answer