Is there a clean, preferably standard method of trimming leading and trailing whitespace from a string in C? I'd roll my own, but I would think this is a common problem with an equally common solution.
相关问题
- Multiple sockets for clients to connect to
- how to split a list into a given number of sub-lis
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Generate string from integer with arbitrary base i
Here's one that shifts the string into the first position of your buffer. You might want this behavior so that if you dynamically allocated the string, you can still free it on the same pointer that trim() returns:
Test for correctness:
Source file was trim.c. Compiled with 'cc trim.c -o trim'.
Here is my attempt at a simple, yet correct in-place trim function.
My solution. String must be changeable. The advantage above some of the other solutions that it moves the non-space part to the beginning so you can keep using the old pointer, in case you have to free() it later.
This version creates a copy of the string with strndup() instead of editing it in place. strndup() requires _GNU_SOURCE, so maybe you need to make your own strndup() with malloc() and strncpy().
Just to keep this growing, one more option with a modifiable string:
These functions will modify the original buffer, so if dynamically allocated, the original pointer can be freed.