01-用cctype库统计字符串的大写、小写、数字、其他字符的个数

测试用例: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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值