distributedlife

passionate about everything

Vanilla C with Sprinkles – Trimming Strings Using one simple function my strings are much more trim Published by Ryan Boucher @ 11:55 pm

I was going to talk about disciplines in software testing but my netbook isn’t connecting to the network and consequently I can’t get the post off. Still I had this one scheduled for the weekend. It’s about strings in old languages like Latin. I’ll retype the other one or fix the network. Till tomorrow!

Implementing the trim function barely gets a mention in languages these days because having to implemented it in a new language is stoopid. However C is old and grizzled.

This version stores the result in a HP Paramater for use outside the function. You could return it if you wanted. If you did you would need to remove the free statement.


void Trim (const char* Bloated, const char* Parameter)
{
    long BloatedLength = strlen (Bloated) ;

    char* Trimmed = 0 ;
    long TrimmedLength = 0 ;

    long TrimFromStart = strspn (Bloated, " \t") ;
    long TrimFromEnd = 0 ;

    long index = 0 ;

We need to calculate the number of characters that are white space at the end of the string. This ignores new line characters.


    //Count Trailing whitespace
    index = BloatedLength - 1 ;
    while ( (Bloated[index] == ' ') || (Bloated[index] == '\t'))
    {
        TrimFromEnd++ ;

        if (index == 0)
        {
            break ;
        }

        index-- ;
    }

    TrimmedLength = BloatedLength - TrimFromEnd - TrimFromStart ;
    TrimmedLength++ ; //space for null terminating

    Trimmed = (char*) malloc (TrimmedLength * sizeof(char)) ;
    if (!Trimmed)
    {
        lr_error_message("Failed to allocate memory for the trimmed string") ;

        return ;
    }

Our actual trim is nothing more than memcpy so you could write a substring function and do it that way.


    //"trim"
    memcpy (Trimmed, Bloated + TrimFromStart, TrimmedLength) ;

    //set null terminating char
    Trimmed[TrimmedLength - 1] = '\0' ;

    lr_set (Trimmed, Parameter);

    free (Trimmed) ;
}
My Mug Ryan Boucher is a Software Inquisitor and is passionate about it. You can find a whole raft of articles and anecdotes about software testing and other topics he gets excited about.
Tags , , , , , , , ,