統計字符串單詞數的兩種方法(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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM