The C languange is not very friendly if you have to handle strings, and at the same time handling strings is a very very very common task for a C programmer. 

Some functions are provided by the standard libraries, but if you need something just a little bit complex (like trimming leading and trailing white spaces) you have to write the function by yourself.

The implementation I use currently is the following one (I found it on the internet):

 

/*+———————————————————–+

  | Function name : trim.                                     |

  | Parameters    :                                           |

  |   str         : the string to trim.                       |

  | Return  value : the pointer to the string.                |

  |               : if an error occurs SU_CANNOT_W_BYTE       |

  | Description   : Trims leading and trailing white spaces   |

  |                 and return the modified string.           |

  |                 The pointer to the strign can be yet used |

  |                 to free memory.                           |

  +———————————————————–+*/

char *trim(char *str)

{

    size_t   len      = 0;

    char     *frontp  = str – 1;

    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(*(++frontp)))

        ;

    while(isspace(*(–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;

}

 

The pro of this implementation is that the function modifies the string passed and so you can free it if you have previously allocated the string using a malloc.

The con is that the function modifies the string passed….

Gg1