Alex Rivera | Logout

Best algorithm to strip leading and trailing spaces in C

Asked 2008-12-09T07:51:33.560
9

What is the best approach in stripping leading and trailing spaces in C?

Edit
Report

2 Answers

24

Here is how linux kernel does the trimming, called strstrip():

char *strstrip(char *s)
{
    size_t size;
    char *end;

    size = strlen(s);

    if (!size)
        return s;

    end = s + size - 1;
    while (end >= s && isspace(*end))
        end--;
    *(end + 1) = '\0';

    while (*s && isspace(*s))
        s++;

    return s;
}

Its basically a better formatted and error-checked version what the previous poster said.

answered 2008-12-09T08:27:30.663
1

If you're on Linux/Windows and have the library glib linked into your program, you can use the the routine g_strstrip().

answered 2009-01-05T06:08:33.457

Your Answer