曲径通幽论坛

标题: 去掉字符串中的空格符 [打印本页]

作者: beyes    时间: 2013-7-7 20:25
标题: 去掉字符串中的空格符
在某些情况下,需要去掉字符串中的空格符,比如将 "hello world" 写成 "helloworld" 。

下面示例程序给出该问题的一个解决算法:
[C++] 纯文本查看 复制代码
#include <stdio.h>
#include <strings.h>

void eatspaces(char *str)
{
        int i = 0;
        int j = 0;

        while ((*(str + i) = *(str + j++)) != '\0')

             if(*(str + i) != ' ')
                i++;

        return;
}


int main()
{
        char array[32] = "hello linux world";

        printf ("before eat spaces : %s\n", array);

        eatspaces(array);

        printf("after eat spaces : %s\n", array);

        return 0;
}

运行输出:
[beyes@groad.net c]$ ./eatspaces
before eat spaces : hello linux world
after eat spaces : hellolinuxworld
这里说明一点,在  while ((*(str + i) = *(str + j++)) != '\0') 循环中,需要注意的是赋值语句的结果并不会永远为真(参考:《
不要以为赋值语句肯定为真
》)。当循环到字符串结束,即遇到 '\0' 时,赋值表达式的结果即为假,或者说为 0,这时 '\0' == '\0',会直接跳出 while 循环,从而结束 eatspaces() 函数。




欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2