home   articles   tags   browse code   

C++ trim function


 

The C++ STL fails us again when it fails to provide trim functions. Trim, ltrim and rtrim are standard string manipulation functions. I use them so often I thought I would provide some here.

#include <iostream>
#include <vector>
#include <string>

using namespace std;

string& trim(string &str);
string& ltrim(string &str);
string& rtrim(string &str);

int main(int argc, char *argv[])
{
    string str1 = " Ni Hao ";
    string str2 = " Bonjour ";
    string str3 = " Hello ";
    cout << str1 << endl;
    cout << "[" << trim(str1) << "]" <<endl;
    cout << str2 << endl;
    cout << "[" << ltrim(str2) << "]" <<endl;
    cout << str3 << endl;
    cout << "[" << rtrim(str3) << "]" <<endl;
}
string& trim(string &str)
{
    int i,j,start,end;

    //ltrim
    for (i=0; (str[i]!=0 && str[i]<=32); )
        i++;
    start=i;

    //rtrim
    for(i=0,j=0; str[i]!=0; i++)
        j = ((str[i]<=32)? j+1 : 0);
    end=i-j;
    str = str.substr(start,end-start);
    return str;
}
string& ltrim(string &str)
{
    int i,j,start,end;

    for (i=0; (str[i]!=0 && str[i]<=32); )
        i++;
    start=i;

    str = str.substr(start,str.length()-start);
    return str;
}
string& rtrim(string &str)
{
    int i,j,start,end;

    for(i=0,j=0; str[i]!=0; i++)
        j = ((str[i]<=32)? j+1 : 0);
    end=i-j;

    str = str.substr(0,end);
    return str;
}
 

Tags: c++
 
John on Jan 25th, 2010 3:30 am said:
This is wrong in so many ways, but most obviously C++ string are not null-terminated for(i=0,j=0; str[i]!=0; i++) is plain wrong.
 

John on Jan 25th, 2010 3:35 am said:
STL strings aren't the best, but here's how I would implement rtrim static string rtrim(const string& s) { return s.substr(0, s.find_last_not_of(" nrtfv") + 1); } It's (hopefully) correct.
 

John on Jan 25th, 2010 3:37 am said:
Difficult to post code to this blog :-( Obviously the string " nrtfv" in the above post is supposed to be a string consisting of the whitespace characters you wish to remove.
 

trim function without string stl on May 9th, 2010 12:35 am said:
http://patnidheeraj.blogspot.com/2010/04/trim-function-c.html
 



 

 



Related Articles
 


home  |  privacy policy  |  terms of use  |  contact  


©2010, Zedwood Digital