Sunday, December 11, 2011

How to trim a std::string?

When dealing with some input, we often want to trim it first. But C++ std::string lacks such a trim function, following is a pretty decent implementation:


       void trim(std::string& str)
        {
          string::size_type pos = str.find_last_not_of(' ');
          if(pos != string::npos) {
                str.erase(pos + 1);
                pos = str.find_first_not_of(' ');
                if(pos != string::npos) str.erase(0, pos);
          }
          else str.erase(str.begin(), str.end());
        }

No comments:

Post a Comment