C++—— 統計字符


統計字符

 

代碼如下:

 1 //#include <iostream>  2 //#include <fstream>  3 //using namespace std;  4 //int main()  5 //{  6 // int English_letters,Space,Number,Other;  7 // char a[100];  8 // cin.get(a[100]);  9 // while (a!="\0"){ 10 // if(a>="a" && a<="z"||a>="A" && a<="Z") English_letters++; 11 //        //"C"表示的是一個字符串的地址,注意這里是雙引號,而不是單引號 12 // else if (a>="0"&&a<="9") Number++; 13 // else if (a==" ") Space++; 14 // else Other++; 15 // }; 16 // cout<<English_letters<<endl; 17 // cout<<Space<<endl; 18 // cout<<Number<<endl; 19 // cout<<Other<<endl; 20 // return 0; 21 //}
22 
23 /*
24 1.輸入完之后按回車之后不會跳出那個輸入那個,還是會在里邊??? 25  因為我寫的是cin>>a[100],100個位置並沒有占滿 26  所以這種情況的處理是,得先知道一共有多少個字符,要不它永遠不會跳出來 27  所以這里就想到了下邊的這種方法,把判斷的過程寫在一個函數中進行封裝,判斷有多少個字符的工作放在主函數中 28 */
29 
30 #include <iostream>
31 #include <fstream> 
32 #include <string.h>    //這里必須是.h的,不能是string,會報錯的 
33 using namespace std; 34 
35 void tongji(char*,int);    //函數的前置聲明 
36 
37 int main() 38 { 39     char a[100]; 40  gets(a); 41     //cin.get函數 一次只能從輸入行中提取一個字符,包括空格和回車鍵都作為一個輸入字符。 
42     int n=strlen(a); 43 // cout<<"n:"<<n<<endl; 這行是用來調試的時候用的,用來看看gets函數是否把所有的字符都傳進來了 
44  tongji(a,n); 45     
46     system("pause"); 47     return 0; 48 } 49 
50     void tongji(char s[],int s1)    //函數的定義 
51 { 52     int num=0,str=0,space=0,other=0; 53     for(int i=0;i<s1;i++) 54  { 55         if((s[i]>='a'&&s[i]<='z')||(s[i]>='A'&&s[i]<='Z')) 56             ++str; 57         else if(s[i]>='0'&&s[i]<='9') 58             ++num; 59         else if(s[i]==' ') 60             ++space; 61         else ++other; 62  } 63     cout<<str<<endl; 64     cout<<space<<endl; 65     cout<<num<<endl; 66     cout<<other<<endl; 67 } 

分析與總結:

  1、這道題學會就是函數寫在主函數之外的思想,把它要判斷的過程進行封裝

  2、還有就是字符串輸入,應該怎么輸入,用哪個函數進行輸入,用這個函數的時候需要包含什么頭文件

  3、測字符串長度的時候用到哪個函數,需要包含的頭文件

   

 

寫在最后:

  哪里有不足或者錯誤的地方,歡迎小伙伴們進行指教,一起進步哦!


免責聲明!

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



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