统计字符串单词数的两种方法(c语言实现)

 问题描述:统计一个字符串,字符串由单词,空格构成。

 

 思路:

  一,遍历字符串所有字符,设置一个布尔变量来判断当前是空格还是字母

    

 1 #include <stdio.h>
 2 #include <stdbool.h>
 3 #include <string.h>
 4 
 5 int count_words(char* s)
 6 {
 7     int len=strlen(s);  // len存放字符串长度
 8     bool isWhite=true;  
 9     int i,count=0;  //count用来计数单词数
10     for(i=0;i<len;i++)
11     {
12         if(*(s+i)==' ')  //当前字符为空
13         {
14             isWhite=true;
15         }else if(isWhite){  // 此句代码被执行表明:当前字符不为空且上个字符为空
16             count++;  //单词数+1
17             isWhite=false;  //进入非空格状态
18         }
19     }
20     return count;
21 }
22 
23 int main()
24 {
25     char* a="i love you ";
26     printf("%d",count_words(a));
27 }

  

  二,遍历字符串所有字符,如果当前字符不为空,单词数+1,再嵌套一个while循环,判断当前单词是否结束

 

 1 #include <stdio.h>
 2 #include <string.h>
 3 
 4 int count_words(char* s)
 5 {    
 6     int len=strlen(s);
 7     int count,i;
 8     for(i=0;i<len;i++)
 9     {
10         if(*(s+i)!=' '){  // 如果当前代码不为空
11             count++;  //单词数+1
12             while(*(s+i)!=' '&& i<len)  //判断当前单词是否结束
13                 i++;
14         }
15     }
16     return count;
17 }
18 
19 int main()
20 {
21     char* a="i love you";
22     printf("%d",count_words(a));
23 }

 

posted @ 2018-09-09 20:28  潇潇雨歇zhj  阅读(4666)  评论(0编辑  收藏  举报