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

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

    For what it's worth, here is a trim implementation with an eye towards performance. It's much quicker than many other trim routines I've seen around. Instead of using iterators and std::finds, it uses raw c strings and indices. It optimizes the following special cases: size 0 string (do nothing), string with no whitespace to trim (do nothing), string with only trailing whitespace to trim (just resize the string), string that's entirely whitespace (just clear the string). And finally, in the worst case (string with leading whitespace), it does its best to perform an efficient copy construction, performing only 1 copy and then moving that copy in place of the original string.

    void TrimString(std::string & str)
    { 
        if(str.empty())
            return;
    
        const auto pStr = str.c_str();
    
        size_t front = 0;
        while(front < str.length() && std::isspace(int(pStr[front]))) {++front;}
    
        size_t back = str.length();
        while(back > front && std::isspace(int(pStr[back-1]))) {--back;}
    
        if(0 == front)
        {
            if(back < str.length())
            {
                str.resize(back - front);
            }
        }
        else if(back <= front)
        {
            str.clear();
        }
        else
        {
            str = std::move(std::string(str.begin()+front, str.begin()+back));
        }
    }
    

提交回复
热议问题