An alternative implementation of Trim() for STL
March 5th, 2008
The C-STL - string.h does provide many functions which are often needed when working with strings.
However, the well-known trim operation is not implemented.
As you probably know is trim or sometimes called strip a common string manipulation function which removes leading and trailing whitespace from a string.
There is no standard trim function in C or C++. Most of the available string libraries for C contain code which implements trimming, or functions that significantly ease an efficient implementation. The function has also often been called EatWhitespace in some, non-standard C libraries.
The open source C++ library Boost has several trim variants. One is:
#include <boost/algorithm/string/trim.hpp> trimmed = boost::algorithm::trim_copy(''string'');
MFC provides a Trim() (which makes problems with VC6) and TrimLeft() / TrimRight() as well.
If you simply need a trim function and not a whole library to be included you can use this.
std::string trim(const std::string& s,const std::string& drop = " ") { std::string::size_type first = s.find_first_not_of( drop ); std::string::size_type last = s.find_last_not_of( drop ); if( first == std::string::npos || last == std::string::npos ) return std::string( "" ); return s.substr( first, last - first + 1 ); }
In addition to string.hI have one more solution for you if you’re being willed using std::string (which doesn’t make much sense in most cases).
Remove whitespaces on the right side:
char* trim_right(char* szSource) { char* pszEOS = 0; // Set pointer to character before terminating NULL pszEOS = szSource + strlen( szSource ) - 1; // iterate backwards until non ' ' is found while( (pszEOS >= szSource) && (*pszEOS == ' ') ) *pszEOS-- = '\0'; return szSource; }
Cut off the left side:
char* trim_left(char* szSource) { char* pszBOS = 0; pszBOS = szSource; // iterate backwards until non ' ' is found while(*pszBOS == ' ') *pszBOS++; return pszBOS; }
Trim both sides:
char* trim(char *szSource) { return trim_left( trim_right( trim_left(szSource) ) ); }
You also can use it with std::string when converting the std::string with c_str() method.
Trim function is very useful together with substring.





