Mimic Python's strip() function in C

sudharsh picture sudharsh · Sep 28, 2009 · Viewed 11.6k times · Source

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.

Answer

Alex Martelli picture Alex Martelli · Sep 28, 2009

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).