c语言如何统计数字字符的个数,请问这个用c怎么做:输入一串字符,分别统计其中数字和字母的个数...

本文介绍了一个简单的C语言程序,用于统计输入字符串中的字母、数字、空格和其他字符的数量。通过使用switch-case结构和循环,程序能够高效地进行字符分类计数。

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼

#include

main()

{

int acount=0,bcount=0,ccount=0,dcount=0;

char a;

printf("请输入一行字符:\n");

a = getchar();

while (a !='\n')

{

switch (a)

{

case'q':

case'w':

case'e':

case'r':

case't':

case'y':

case'u':

case'i':

case'o':

case'p':

case'a':

case's':

case'd':

case'f':

case'g':

case'h':

case'j':

case'k':

case'l':

case'z':

case'x':

case'c':

case'v':

case'b':

case'n':

case'm':

case'Q':

case'W':

case'E':

case'R':

case'T':

case'Y':

case'U':

case'I':

case'O':

case'P':

case'A':

case'S':

case'D':

case'F':

case'G':

case'H':

case'J':

case'K':

case'L':

case'Z':

case'X':

case'C':

case'V':

case'B':

case'N':

case'M':

acount++;break;

case'1':

case'2':

case'3':

case'4':

case'5':

case'6':

case'7':

case'8':

case'9':

case'0':

bcount++;break;

case' ':

ccount++;break;

default:

dcount++;break;

}

a= getchar();

}

printf("字母数:%d\n空格数:%d\n数字数:%d\n其他字符:%d\n",acount,ccount,bcount,dcount);

}

在C语言中,实现输入一个字符串并分别统计其中英文字母、空格、数字其它字符个数,有以下两种常见方法: ### 方法一:使用`ctype.h`库函数 ```c #include <stdio.h> #include <ctype.h> // 统计字符类型 void count_characters(char str[], int *letters, int *digits, int *spaces, int *others) { *letters = *digits = *spaces = *others = 0; for (int i = 0; str[i] != '\0'; i++) { if (isalpha(str[i])) { (*letters)++; } else if (isdigit(str[i])) { (*digits)++; } else if (isspace(str[i])) { (*spaces)++; } else { (*others)++; } } } int main() { char str[100]; int letters, digits, spaces, others; printf("输入一个字符串:"); scanf("%[^\n]", str); count_characters(str, &letters, &digits, &spaces, &others); printf("字母:%d\n数字:%d\n空格:%d\n其他字符:%d\n", letters, digits, spaces, others); return 0; } ``` 此方法定义了`count_characters`函数,它接收一个字符四个指针,用于存储字母数字、空格其他字符的数量。在`main`函数中,用户输入字符串,调用`count_characters`函数进行统计,并输出结果[^1]。 ### 方法二:手动判断字符范围 ```c #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { char ch; int letter = 0, digital = 0, space = 0, other = 0; while((ch = getchar())!= '\n') { if( ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z' ) { letter++; } else if(ch >= '0' && ch <= '9' ) { digital++; } else if(ch == ' ') { space++; } else { other++; } } printf("字母=%d,数字=%d,空格=%d,其它字符=%d\n", letter, digital, space, other); return 0; } ``` 该方法在`main`函数中使用`getchar`逐个读取字符,直至遇到换行符。通过手动判断字符范围来统计各类字符的数量,并输出结果[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值