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?
The reason trim() isn’t in the standard library is that when the last standard was made, they had to strike a balance between formalizing current behavior (adding nothing new, just stabilizing what already existed), and adding new functionality. In general, they preferred not to add a feature unless it either 1) would be impossible otherwise, or 2) there were significant drawbacks to using third-party libraries instead. Making too many changes would
With trim(), there are no major interoperability issues. As long as your third-party trim() implementation takes a string and returns a string, we don’t really care where it’s defined. So it’s not really necessary In the standard library. It can be easily supplied by other libraries.
By contrast, something like the string class or vector, are classes that the standard library must supply, because if you use a custom string class, only string operations from that library will work. With a standard library string, third-party libraries can target this common string definition, and everyone wins.
When the last standard came out, Herb Sutter wrote a post describing this very well here
Of course, it would be nice to have a trim() function, but they had bigger fish to fry. They had to standardize all the basics first. I don’t think C++0x will add a trim function, but it will add a lot of other convenience utilities that back in ’98 were considered ‘unnecessary’ or too specialized.