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

user34537 picture user34537 · Jan 26, 2009 · Viewed 14.3k times · Source

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(" \n\r\t");
    size_t e = str.find_last_not_of (" \n\r\t");

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

test: cout << trim(" \n\r\r\n \r\n text here\nwith return \n\r\r\n \r\n "); -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?

Answer

BobbyShaftoe picture BobbyShaftoe · Jan 26, 2009

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\n\r\t\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 );
}