码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-09-09 21:03:21      阅读:265      评论:0      收藏:0      [点我收藏+]

标签:col   clu   单词   执行   遍历   两种   else   统计   pre   

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

 

 思路:

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

    

 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 }

 

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

标签:col   clu   单词   执行   遍历   两种   else   统计   pre   

原文地址:https://www.cnblogs.com/kiritozhj/p/9614931.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!