What's the best way to trim std::string?

后端 未结 30 2890
无人及你
无人及你 2020-11-21 22:13

I\'m currently using the following code to right-trim all the std::strings in my programs:

std::string s;
s.erase(s.find_last_not_of(\" \\n\\r\\         


        
30条回答
  •  说谎
    说谎 (楼主)
    2020-11-21 22:55

    The above methods are great, but sometimes you want to use a combination of functions for what your routine considers to be whitespace. In this case, using functors to combine operations can get messy so I prefer a simple loop I can modify for the trim. Here is a slightly modified trim function copied from the C version here on SO. In this example, I am trimming non alphanumeric characters.

    string trim(char const *str)
    {
      // Trim leading non-letters
      while(!isalnum(*str)) str++;
    
      // Trim trailing non-letters
      end = str + strlen(str) - 1;
      while(end > str && !isalnum(*end)) end--;
    
      return string(str, end+1);
    }
    

提交回复
热议问题