Avatar ·

How to properly remove spaces at the beginning and end of std::string in C++?

Hello everyone! I'm a beginner C++ developer, and I have a seemingly simple task: I need to trim spaces (and any whitespace characters) at the beginning and end of a string. I'm working with std::string. I tried writing my own trim function using loops and character checking with std::isspace, but the code turned out bulky and, in my opinion, inefficient. Here's what I came up with so far: ```cpp #include #include #include std::string trim(std::string str) { // Remove spaces at the beginning while (!str.empty() && std::isspace(str[0])) { str.erase(0, 1); } // Remove spaces at the end while (!str.empty() && std::isspace(str[str.length() - 1])) { str.erase(str.length() - 1, 1); } return str; } ```