Strip leading and trailing space in C

This is an example C program illustrating stripping leading and trailing spaces from a string using the library function isspace.

#include <stdio.h>
/* For strlen. */
#include <string.h>
/* For "malloc". */
#include <stdlib.h>
/* For "isspace" */
#include <ctype.h>

/* This takes "word" and strips leading and trailing spaces from it,
   returning the result in allocated memory. For convenience, if the
   word has no leading or trailing spaces, it just duplicates the
   word. */

static char *
strip_spaces (const char * word)
{
    int l;
    int n;
    const char * word_begins;
    const char * word_ends;

    l = strlen (word);
    n = l;
    word_begins = word;
    while (isspace (*word_begins)) {
        word_begins++;
        n--;
    }
    word_ends = word + l - 1;
    while (isspace (*word_ends)) {
        word_ends--;
        n--;
    }
    if (n == l) {
        return strdup (word);
    }
    else {
        char * copy;
        int i;

        copy = malloc (n + sizeof ((char) '\0'));
        if (! copy) {
            fprintf (stderr, "Out of memory.\n");
            exit (EXIT_FAILURE);
        }
        for (i = 0; i < n; i++) {
            copy[i] = word_begins[i];
        }
        copy[n] = '\0';
        return copy;
    }
}

int main ()
{
    const char * examples[] = {
        "  now    ",
        "\t\tis   ",
        "the",
        "winter\n\n\n",
        "     of     ",
        "\n\nour\t\t",
        "discontent.",
    };
    int n_examples;
    int i;

    n_examples = sizeof (examples) / sizeof (examples[0]);
    for (i = 0; i < n_examples; i++) {
        char * trimmed;

        trimmed = strip_spaces (examples[i]);
        printf ("<%s> -> <%s>\n", examples[i], trimmed);
        /* Because the word is always duplicated, we don't need to
           think about whether to free it or not. */
        free (trimmed);
    }
    return 0;
}

(download)

The output of the example looks like this:

<  now    > -> <now>
<		is   > -> <is>
<the> -> <the>
<winter


> -> <winter>
<     of     > -> <of>
<

our		> -> <our>
<discontent.> -> <discontent.>


Copyright © Ben Bullock 2009-2023. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer