LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Best method to trim left/right a string in C? (https://www.linuxquestions.org/questions/programming-9/best-method-to-trim-left-right-a-string-in-c-4175606293/)

Xeratul 05-19-2017 11:25 AM

Best method to trim left/right a string in C?
 
Hello,

I am employing usually the following function:

Trim is really useful and important if you programme in C.
There are usually the need to trim configuration files, to let the programme explore the content of user settings.

Code:

char *trim(char *str)
{
    size_t len = 0;
    char *frontp = str;
    char *endp = NULL;

    if( str == NULL ) { return NULL; }
    if( str[0] == '\0' ) { return str; }

    len = strlen(str);
    endp = str + len;

    /* Move the front and back pointers to address the first non-whitespace
    * characters from each end.
    */
    while( isspace((unsigned char) *frontp) ) { ++frontp; }
    if( endp != frontp )
    {
        while( isspace((unsigned char) *(--endp)) && endp != frontp ) {}
    }

    if( str + len - 1 != endp )
            *(endp + 1) = '\0';
    else if( frontp != str &&  endp == frontp )
            *str = '\0';

    /* Shift the string so that it starts at str so that if it's dynamically
    * allocated, we can still free it on the returned pointer.  Note the reuse
    * of endp to mean the front of the string buffer now.
    */
    endp = str;
    if( frontp != str )
    {
            while( *frontp ) { *endp++ = *frontp++; }
            *endp = '\0';
    }


    return str;
}

I recently made again another one, which does similar job of trimming left and right.

You can share your experience with trim.

Laserbeak 05-20-2017 10:22 PM

I'm really still not sure exactly what you are trying to do here... get rid of everything before the first whitespace and after the last?

GazL 05-21-2017 04:01 AM

You might want to take look at strtok(3) if this is about parsing user options:
Code:

test@ws1:/tmp$ cat strtok.c
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
        static char string[] = { "\t\t    option1=100,option2=200    " };

        char *s = string;
        char *token = NULL;

        while (( token  = strtok(s, " \t,") )) {
                printf("\"%s\"\n", token);
                s = NULL ;  /* strtok() only wants the pointer on the first invocation */
        }

        return 0;
}
test@ws1:/tmp$ cc -Wall -o strtok strtok.c
test@ws1:/tmp$ ./strtok
"option1=100"
"option2=200"
test@ws1:/tmp$

You would have to add additional code to cope with any embedded spaces in quoted strings such as a option3="a string with whitespace, and a comma.", and I get the feeling that could get quite torturous, but if they're not a consideration then it'll do the job of removing leading/trailing whitespace.


All times are GMT -5. The time now is 06:26 PM.