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

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

    My solution based on the answer by @Bill the Lizard.

    Note that these functions will return the empty string if the input string contains nothing but whitespace.

    const std::string StringUtils::WHITESPACE = " \n\r\t";
    
    std::string StringUtils::Trim(const std::string& s)
    {
        return TrimRight(TrimLeft(s));
    }
    
    std::string StringUtils::TrimLeft(const std::string& s)
    {
        size_t startpos = s.find_first_not_of(StringUtils::WHITESPACE);
        return (startpos == std::string::npos) ? "" : s.substr(startpos);
    }
    
    std::string StringUtils::TrimRight(const std::string& s)
    {
        size_t endpos = s.find_last_not_of(StringUtils::WHITESPACE);
        return (endpos == std::string::npos) ? "" : s.substr(0, endpos+1);
    }
    

提交回复
热议问题