Friday, June 22, 2007

Implementing String trimming (Ltrim and Rtrim) in C

Here is a simple implementation of implementing a simple Left trim (ltrim) and Right trim(rtim) of unwanted characters from a C style string. (null terminated strings). Doesn't suffer the overheads of the memmove implementation in which the worst case scenario (a string containing all junk characters) is approx. N^2 / 2.
#include 

char* rtrim(char* string, char junk);
char* ltrim(char* string, char junk);

int main()
{
    char testStr1[] = "     We like helping out people          ";
    char testStr2[] = "     We like helping out people          ";
    char testStr3[] = "     We like helping out people          ";
    printf("|%s|", testStr1);
    printf("\n|%s|", ltrim(testStr1, ' '));
    printf("\n\n|%s|", testStr2);
    printf("\n\n|%s|", rtrim(testStr2, ' '));
    printf("\n\n|%s|", testStr3);
    printf("\n|%s|", ltrim(rtrim(testStr3, ' '), ' '));
    getchar();
    return 0;
}


char* rtrim(char* string, char junk)
{
    char* original = string + strlen(string);
    while(*--original == junk);
    *(original + 1) = '\0';
    return string;
}

char* ltrim(char *string, char junk)
{
    char* original = string;
    char *p = original;
    int trimmed = 0;
    do
    {
        if (*original != junk || trimmed)
        {
            trimmed = 1;
            *p++ = *original;
        }
    }
    while (*original++ != '\0');
    return string;
}
/*

|     We like helping out people          |
|We like helping out people          |

|     We like helping out people          |

|     We like helping out people|

|     We like helping out people          |
|We like helping out people|

 */
 
Blogger Template Layout Design by [ METAMUSE ] : Code Name Gadget 1.1 Power By freecode-frecode.blogger.com & blogger.com Programming Blogs - BlogCatalog Blog Directory