How to trim a string in C

Trim a string

The problem of removing leading and trailing whitespace characters in strings occurs in programming quite often. Here is a solution.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

void trim (char *dest, char *src); 

int main (int argc, char **argv)
{
    char inbuf [1024];
    char outbuf [1024];

    printf ("Type a string : ");
    while (fgets (inbuf, 1024, stdin) != NULL) {
        trim (outbuf, inbuf);      
        printf ("input string -%s-\n\n", inbuf);
        printf ("string -%s-\n\n", outbuf);
        printf ("Type a string : ");
    }

}

// trim: leading and trailing whitespace of string
void trim (char *dest, char *src)
{
    if (!src || !dest)
       return;

    int len = strlen (src);

    if (!len) {
        *dest = '\0';
        return;
    }
    char *ptr = src + len - 1;

    // remove trailing whitespace
    while (ptr > src) {
        if (!isspace (*ptr))
            break;
        ptr--;
    }

    ptr++;

    char *q;
    // remove leading whitespace
    for (q = src; (q < ptr && isspace (*q)); q++)
        ;

    while (q < ptr)
        *dest++ = *q++;

    *dest = '\0';
}

We can compile and run the above program.… Read more