Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mimic Python's strip() function in C

I started on a little toy project in C lately and have been scratching my head over the best way to mimic the strip() functionality that is part of the python string objects.

Reading around for fscanf or sscanf says that the string is processed upto the first whitespace that is encountered.

fgets doesn't help either as I still have newlines sticking around. I did try a strchr() to search for a whitespace and setting the returned pointer to '\0' explicitly but that doesn't seem to work.

like image 244
sudharsh Avatar asked Sep 28 '09 17:09

sudharsh


People also ask

What does Strip () function do in Python?

The Strip() method in Python removes or truncates the given characters from the beginning and the end of the original string. The default behavior of the strip() method is to remove the whitespace from the beginning and at the end of the string.

What is input () Strip () in Python?

strip() is an inbuilt function in Python programming language that returns a copy of the string with both leading and trailing characters removed (based on the string argument passed). Syntax: string.

What does Strip do in C?

returns string with leading or trailing characters or both removed, based on the option you specify.

What does Strip () return?

The strip() method returns a copy of the string by removing both the leading and the trailing characters (based on the string argument passed).


2 Answers

Python strings' strip method removes both trailing and leading whitespace. The two halves of the problem are very different when working on a C "string" (array of char, \0 terminated).

For trailing whitespace: set a pointer (or equivalently index) to the existing trailing \0. Keep decrementing the pointer until it hits against the start-of-string, or any non-white character; set the \0 to right after this terminate-backwards-scan point.

For leading whitespace: set a pointer (or equivalently index) to the start of string; keep incrementing the pointer until it hits a non-white character (possibly the trailing \0); memmove the rest-of-string so that the first non-white goes to the start of string (and similarly for everything following).

like image 145
Alex Martelli Avatar answered Oct 17 '22 23:10

Alex Martelli


There is no standard C implementation for a strip() or trim() function. That said, here's the one included in the Linux kernel:

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;
}
like image 44
Mark Avatar answered Oct 17 '22 23:10

Mark