您的位置:首页 > 其它

统计一个字符串中的单词的个数,并打印各个单词

2014-06-05 11:39 387 查看
/*测试数据:Shen zhen is a beautiful city!*/
/*运行结果:Word:6
Shen
zhen
is
a
beautiful
city!*/
#include<stdio.h>
#define SIZE 1000

void wordCount(char *str)
{
int count = 0, flag = 0;
char *p = str;
while (*p != '\0'){
while (*p == 32){
if (*(p + 1) == 0){/*当空白的下一位是结束符时,意味着最后一个单词后面是空格,那么就做一个标记,让下面的程序看到*/
flag = 1;
}
++p;
}
while (*p != 0 && *p != 32){
++p;
}
if (!flag){/*根据上面的标记,知道这个时候不是单词结束了,而是句子要结束了,不再统计单词个数了*/
++count;
}
}
printf("Word:%d\n", count);
p = str;
flag = 0;
while (*p != 0){
while (*p == 32){
if (*(p + 1) == 0){/*和上面的一样*/
flag = 1;
}
++p;
}
while (*p != 0 && *p != 32){
putchar(*p);
++p;
}
if (!flag){
putchar(10);
}
}

}

int main()
{
char str[SIZE];
printf("Please enter a string :\n");
gets(str);
wordCount(str);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c 单词分离
相关文章推荐