2011-08-23 83 views
0

可能重复:
How do I trim leading/trailing whitespace in a standard way?去掉空格

我需要从开始和字符串实例的结尾删除所有空格,如果我的字符串

"  hello  world.  " 

(不带引号),我需要打印

"hello  world." 

我想是这样的:

size_t length = strlen (str); 
for (newstr = str; *newstr; newstr++, length--) { 
    while (isspace (*newstr)) 
     memmove (newstr, newstr + 1, length--); 

但它删除所有空格。

我该如何解决?

+0

的可能的复制http://stackoverflow.com/questions/122616/painless-way-to-trim-leading-trailing-whitespace-in-c和http://stackoverflow.com/questions/656542/trim-a-string-in-c – lhf

+0

这是功课吗? –

+0

请参阅此SO问题的答案:http://stackoverflow.com/questions/122616/painless-way-to-trim-leading-trailing-whitespace-in-c –

回答

3

不需要移动。从起点开始(扫描直到第一个非空格字符)。然后,从后面开始工作,找到第一个非空白字符。向前移动一个,然后替换为空终止符。

char *s = str; 
while(isspace(*s)) ++s; 
char *t = str + strlen(str); 
while(isspace(*--t)); 
*++t = '\0'; 
+0

太聪明太棒了! – user123

6

跳过开头的空间与while(isspace(...)),然后memmove从你到达开始位置的字符串(您也可以手动执行memmove工作,两个指针的经典的“绝招”,一个用于读一个用于写入)。

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] 

然后,在字符串的结尾移动鼠标指针(你可以帮自己一个strlen),和倒退,直到找到一个非空字符。将它后面的字符设置为0,并且您只需将字符串末尾的空格剪掉即可。

         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!