测试用例:Hello,My name is Dashuaige,I’m 12 years old.
1.方法一:笨办法
我们一般统计字符串中大写、小写、数字、其他字符的个数都是用的笨办法
#include<stdio.h>
#include<string.h>
int main() {
char str[100]="Hello,My name is Dashuaige,I'm 12 years old.";
int i=0;
int SZ=0;//统计数字
int DX=0;//统计大写字母
int XX=0;//统计小写字母
int others=0;//统计其他字符
for(int i=0;i<100;i++) {
if(str[i]>='A'&& str[i]<='Z') {
DX++;
}else if(str[i]>='a'&& str[i]<='z'){
XX++;
}else if(str[i]>='0'&&str[i]<='9') {
SZ++;
}else{
others++;
}
}
printf("大写字母个数为:%d\n",DX);
printf("小写字母个数为:%d\n",XX);
printf("数字个数为: %d\n",SZ);
printf("其他字符个数为:%d\n",others);
return 0;
}
虽然也可行,但C标准库头文件有现有的库 ,用现成的轮子何乐而不为呢?
<ctype.h> 用来确定包含于字符数据中的类型的函数
具体代码为:
#include<stdio.h>
#include<cctype>
#include<string.h>
int main() {
char str[100]="Hello,My name is Dashuaige,I'm 12 years old.";
int i=0;
int SZ=0;//统计数字
int DX=0;//统计大写字母
int XX=0;//统计小写字母
int others=0;//统计其他字符
while(str[i]!='\0') {
if(isupper(str[i]))
++DX;//da xie
else if(islower(str[i]))
++XX;
else if(isalnum(str[i]))
++SZ;
else ++others;
i++;
}
printf("大写字母个数为:%d\n",DX);
printf("小写字母个数为:%d\n",XX);
printf("数字个数为: %d\n",SZ);
printf("其他字符个数为:%d\n",others);
return 0;
}