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
I know there have many answers, but I post my answer here to see if my solution is good enough.
Here i use the dynamic memory allocation to trim the input string to the function trimStr. First, we find how many non-empty characters exist in the input string. Then, we allocate a character array with that size and taking care of the null terminated character. When we use this function, we need to free the memory inside of main function.
Use a string library, for instance:
...as you say this is a "common" problem, yes you need to include a #include or so and it's not included in libc but don't go inventing your own hack job storing random pointers and size_t's that way only leads to buffer overflows.
A bit late to the game, but I'll throw my routines into the fray. They're probably not the most absolute efficient, but I believe they're correct and they're simple (with
rtrim()
pushing the complexity envelope):I'm only including code because the code posted so far seems suboptimal (and I don't have the rep to comment yet.)
strndup()
is a GNU extension. If you don't have it or something equivalent, roll your own. For example:Personally, I'd roll my own. You can use strtok, but you need to take care with doing so (particularly if you're removing leading characters) that you know what memory is what.
Getting rid of trailing spaces is easy, and pretty safe, as you can just put a 0 in over the top of the last space, counting back from the end. Getting rid of leading spaces means moving things around. If you want to do it in place (probably sensible) you can just keep shifting everything back one character until there's no leading space. Or, to be more efficient, you could find the index of the first non-space character, and shift everything back by that number. Or, you could just use a pointer to the first non-space character (but then you need to be careful in the same way as you do with strtok).