How to trim a string in C

  • Post author:
  • Post last modified:November 13, 2024
  • Reading time:2 mins read

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.

$ gcc trim.c -o trim
$ ./trim
Type a string :     Hello   world     
input string -    Hello   world     
-

string -Hello   world-

Type a string :

Karunesh Johri

Software developer, working with C and Linux.
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments