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

后端 未结 30 3421
无人及你
无人及你 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:38

    Here's a solution easy to understand for beginners not used to write std:: everywhere and not yet familiar with const-correctness, iterators, STL algorithms, etc...

    #include 
    #include  // for isspace
    using namespace std;
    
    
    // Left trim the given string ("  hello!  " --> "hello!  ")
    string left_trim(string str) {
        int numStartSpaces = 0;
        for (int i = 0; i < str.length(); i++) {
            if (!isspace(str[i])) break;
            numStartSpaces++;
        }
        return str.substr(numStartSpaces);
    }
    
    // Right trim the given string ("  hello!  " --> "  hello!")
    string right_trim(string str) {
        int numEndSpaces = 0;
        for (int i = str.length() - 1; i >= 0; i--) {
            if (!isspace(str[i])) break;
            numEndSpaces++;
        }
        return str.substr(0, str.length() - numEndSpaces);
    }
    
    // Left and right trim the given string ("  hello!  " --> "hello!")
    string trim(string str) {
        return right_trim(left_trim(str));
    }
    

    Hope it helps...

提交回复
热议问题