Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

trim is not part of the standard c/c++ library?

Is it me or are there no standard trim functions in the c or c++ library? is there any single function that acts as a trim? If not can anyone tell me Why trim is not part of the standard library? (i know trim is in boost)

My trim code is

std::string trim(const std::string &str)
{
    size_t s = str.find_first_not_of(" 

");
    size_t e = str.find_last_not_of (" 

");

    if(( string::npos == s) || ( string::npos == e))
        return "";
    else
        return str.substr(s, e-s+1);
}

test: cout << trim(" text here with return "); -edit- i mostly wanted to know why it wasnt in the standard library, BobbyShaftoe answer is great. trim is not part of the standard c/c++ library?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No, you have to write it yourself or use some other library like Boost and so forth.

In C++, you could do:

#include <string>

const std::string whiteSpaces( " f

v" );


void trimRight( std::string& str,
      const std::string& trimChars = whiteSpaces )
{
   std::string::size_type pos = str.find_last_not_of( trimChars );
   str.erase( pos + 1 );    
}


void trimLeft( std::string& str,
      const std::string& trimChars = whiteSpaces )
{
   std::string::size_type pos = str.find_first_not_of( trimChars );
   str.erase( 0, pos );
}


void trim( std::string& str, const std::string& trimChars = whiteSpaces )
{
   trimRight( str, trimChars );
   trimLeft( str, trimChars );
} 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...