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'm not sure what you consider "painless."
C strings are pretty painful. We can find the first non-whitespace character position trivially:
We can find the last non-whitespace character position with two similar trivial moves:
(I have spared you the pain of using the
*
and++
operators at the same time.)The question now is what do you do with this? The datatype at hand isn't really a big robust abstract
String
that is easy to think about, but instead really barely any more than an array of storage bytes. Lacking a robust data type, it is impossible to write a function that will do the same as PHperytonby'schomp
function. What would such a function in C return?What do you think about using StrTrim function defined in header Shlwapi.h.? It is straight forward rather defining on your own.
Details can be found on:
http://msdn.microsoft.com/en-us/library/windows/desktop/bb773454(v=vs.85).aspx
If you have
char ausCaptain[]="GeorgeBailey ";
StrTrim(ausCaptain," ");
This will give
ausCaptain
as"GeorgeBailey"
not"GeorgeBailey "
.s was so extremely helpful, I wanted to say I was glad this post was available and to show what I was able to do with the examples. I needed to tokenize a larger string, and then take the substring(s) and find the last one - so I could remove a newline from fgets() call, and also remove the whitespace from the front of that token -- so I could easily compare it with a static string. The first example in the post above got me there, so thank you. Here is how I used the code samples and the output I got.
}
Output
Here's a solution similar to @adam-rosenfields in-place modification routine but without needlessly resorting to strlen(). Like @jkramer, the string is left-adjusted within the buffer so you can free the same pointer. Not optimal for large strings since it does not use memmove. Includes the ++/-- operators that @jfm3 mentions. FCTX-based unit tests included.
Late to the trim party
Features:
1. Trim the beginning quickly, as in a number of other answers.
2. After going to the end, trimming the right with only 1 test per loop. Like @jfm3, but works for an all white-space string)
3. To avoid undefined behavior when
char
is a signedchar
, cast*s
tounsigned char
.@chqrlie commented the above does not shift the trimmed string. To do so....