统计单词数 - 云代码 http://yuncode.net/code/c_50b56eff6668752

 

  1. /* 统计单词数 */ 
  2. #include <stdio.h>  
  3. #include <string.h>  
  4.  
  5. #define MAX_STRING 200                                  /* 数组容量 */  
  6.  
  7. int main(void) {  
  8.     char str[MAX_STRING] = { 0 }; /* 定义str,并初始化为全0 */ 
  9.     int i = 0;  
  10.     int length = 0;  
  11.     int count = 0;  
  12.  
  13.     /* 输入字符数组 */ 
  14.     printf("Input original String:");  
  15.     gets(str); /* 为str赋值 */ 
  16.  
  17.     length = strlen(str); /* 获得输入str的长度 */ 
  18.  
  19.     /* 统计单词个数 */ 
  20.     for (i = 0; i < length; ++i) {  
  21.         if (str[i] != ' ') { /* 单词开始 */ 
  22.             ++count;  
  23.             while (' ' != str[i] && '\0' != str[i]) /* 单词结束 */ 
  24.                 ++i;  
  25.         }  
  26.     }  
  27.  
  28.     printf("There are %d words in \"%s\".\n"/* 输出统计结果 */ 
  29.     count, str);  
  30.  
  31.     return 0;