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

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

    Use the following code to right trim (trailing) spaces and tab characters from std::strings (ideone):

    // trim trailing spaces
    size_t endpos = str.find_last_not_of(" \t");
    size_t startpos = str.find_first_not_of(" \t");
    if( std::string::npos != endpos )
    {
        str = str.substr( 0, endpos+1 );
        str = str.substr( startpos );
    }
    else {
        str.erase(std::remove(std::begin(str), std::end(str), ' '), std::end(str));
    }
    

    And just to balance things out, I'll include the left trim code too (ideone):

    // trim leading spaces
    size_t startpos = str.find_first_not_of(" \t");
    if( string::npos != startpos )
    {
        str = str.substr( startpos );
    }
    

提交回复
热议问题