Advertisement

Elegant space trimming...

Started by April 03, 2001 11:58 PM
1 comment, last by gimp 23 years, 10 months ago
in vb there was a command known as Trim() that was used to remove the leading\training whitespace from strings. I recreated this in C++ when learning but never found a better way of doing it. Any suggestions?
  
inline void LTrim(std::string &a_Data)
{
	while(isspace(a_Data[0]))
		a_Data.erase(a_Data.begin(),a_Data.begin()+1);
}


void RTrim(std::string &a_Data)
{
	while(isspace(a_Data[a_Data.size()-1]))
		a_Data.erase(a_Data.end()-1,a_Data.end());
}


void Trim(std::string &a_Data)
{
	RTrim(a_Data);
	LTrim(a_Data);
} 
  
Thanks Chris
Chris Brodie
It depends on how inportant keeping isspace's definition of whitespace is to you. I sometimes do this.

  class whitestring_global_t {string s;public:whitestring_global_t() {  s.reserve(256);  for(int i=0;i<256;i++) if(isspace(i)) s += (char)i;}operator string()(return s;}} whitestring;// whitestring is now a global, it contains all the characters// that isspace considers space.void TrimL(string &s,cosnt string &wstr=whitestring) {  s.erase(0,s.find_first_not_of(wstr));}void TrimR(string &s,const string &wstr=whitestring) {  s.resize(s.find_last_not_of(wstr)+1);}void Trim(string &s,const string &wstr=whitestring) {  TrimL(s,wstr);  TrimR(s,wstr);}  


Not really that different, except we pass most of the work to member functions and our definition of whitespace is a string
of examples. If we want to use a function to decide what is whitespace, and get all generic we could also do

    bool notspace(char c) { return !isspace(c);}void GTrim(string &s) {  s.erase(s.begin(),find_if(s.begin(),s.end(),notspace));  s.erase(&*find_if(s.rbegin(),s.rend(),notspace)+1,s.end());}    


operator * applied to a reverse_itterator returns a reference to the basic type, in this case a char, I then take this chars address and add one before passing it to erase.

Edited by - Grib on April 4, 2001 11:21:50 AM
Advertisement
Very nice reply. Thank you very much grib...again...
Chris Brodie

This topic is closed to new replies.

Advertisement