Removing spaces from a string in C [duplicate]
Possible Duplicate:
How do I trim leading/trailing whitespace in a standard 开发者_开发技巧way?
I need to remove all spaces from the beginning and at the end of the string for instance if my string is
" hello world. "
(without quotes), I need to print
"hello world."
I tried something like this:
size_t length = strlen (str);
for (newstr = str; *newstr; newstr++, length--) {
while (isspace (*newstr))
memmove (newstr, newstr + 1, length--);
but it removes all spaces.
How can I fix it?
Skip the spaces at the beginning with a while(isspace(...))
, and then memmove
the string from the position you reached to the beginning (you can also do the memmove
work manually with the classic "trick" of the two pointers, one for read and one for write).
You start from
[ ][ ][H][e][l][l][o][ ][W][o][r][l][d][ ][ ][\0]
^
[ ][ ][H][e][l][l][o][ ][W][o][r][l][d][ ][ ][\0]
^ skipping the two spaces you move your pointer here
... and with a memmove you have...
[H][e][l][l][o][ ][W][o][r][l][d][ ][ ][\0]
Then, move your pointer at the end of the string (you can help yourself with a strlen
), and go backwards until you find a non-space character. Set the character after it to 0
, and voilà, you just cut the spaces off the end of your string.
v start from the end of the string
[H][e][l][l][o][ ][W][o][r][l][d][ ][ ][\0]
... move backwards until you find a non-space character...
v
[H][e][l][l][o][ ][W][o][r][l][d][ ][ ][\0]
.... set the character after it to 0 (i.e. '\0')
[H][e][l][l][o][ ][W][o][r][l][d][\0]
... profit!
No need to memmove. Just start at the starting point (scan until first nonspace character). Then, work from the back and find the first non-space character. Move ahead one and then replace with a null termination character.
char *s = str;
while(isspace(*s)) ++s;
char *t = str + strlen(str);
while(isspace(*--t));
*++t = '\0';
精彩评论