统计字符
代码如下:
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、测字符串长度的时候用到哪个函数,需要包含的头文件
写在最后:
哪里有不足或者错误的地方,欢迎小伙伴们进行指教,一起进步哦!