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

后端 未结 30 2955
无人及你
无人及你 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条回答
  •  猫巷女王i
    2020-11-21 22:42

    Here is a straight forward implementation. For such a simple operation, you probably should not be using any special constructs. The build-in isspace() function takes care of various forms of white characters, so we should take advantage of it. You also have to consider special cases where the string is empty or simply a bunch of spaces. Trim left or right could be derived from the following code.

    string trimSpace(const string &str) {
       if (str.empty()) return str;
       string::size_type i,j;
       i=0;
       while (i0 && isspace(str[j])) --j; // the j>0 check is not needed
       while (isspace(str[j])) --j
       return str.substr(i, j-i+1);
    }
    

提交回复
热议问题