Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best algorithm to strip leading and trailing spaces in C [duplicate]

Tags:

c

string

trim

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

like image 530
ksuralta Avatar asked Dec 09 '08 07:12

ksuralta


1 Answers

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.

like image 155
Tuminoid Avatar answered Oct 18 '22 17:10

Tuminoid