trim, ltrim, and rtrim in C





7
Date Submitted Tue. Sep. 26th, 2006 1:13 PM
Revision 1 of 1
Scripter sehrgut
Tags C | ltrim | Parse | rtrim | String | trim
Comments 1 comments
The modus operandi for this is similar to that taken by PHP's implementation of such functions. It's comparitively memory-intensive, but is much faster than running a whole bunch of tests.

Basically, you set a mask -- an array of 256 null bytes -- and set those that correspond to characters you wish to trim. Then, rather than having to test if a character is in the set of characters to trim(O(n), or linear time on *ws), you just test once (O(1), or unit time) to see if the byte in question is set.

And of course, to trim(), you just wrap trim() around both ltrim() and rtrim().

One point of caution: these functions trim in place, so copy strings before trimming them. (Of course, if you usually want access to both pre- and post-trimmed strings, you could always make these malloc() a new string and return a pointer to it . . . )
int          sgstr_ltrim  (char *string, char *ws) {
        char    mask[256];

        int i;
        for(i=0; i<256; i++) {
                mask[i]  =        '\0';
                }
        while(*ws) {
                mask[(uchar)*ws]        =       *ws;
                ws++;
                }

        char *ptr              =      string;
        while(*ptr) {
                if(mask[(uchar)*ptr]) {
                        ptr++;
                        }
                else {
                        break;
                        }
                }

        while(*ptr && ptr != string) {  // shift the string until we reach \0
                *string   =        *ptr;
                ptr++;
                string++;
                }

                *string   =        *ptr;   // now copy over our null terminus

        return 0;
        }
int          sgstr_rtrim (char *string, char *ws) {
        char    mask[256];

        int i;
        for(i=0; i<256; i++) {
                mask[i]  =        '\0';
                }
        while(*ws) {
                mask[(uchar)*ws]        =       *ws;
                ws++;
                }

        int len  =        strlen(string);

        while(len) {
                len--;
                if(mask[(uchar)string[len]]) {
                        string[len]          =    '\0';
                        }
                else {
                        break;
                        }
                }

        return 0;
        }

Keith B

alphahelical.com
I've got good news, and I've got bad news:
The universe is merely a figment of my imagination.
Now are you ready for the bad news?

Comments

Comments Is implementation faster?
Wed. Sep. 27th, 2006 12:30 AM    Newbie timdooling

Voting