输入一行字符,统计其中字母个数,数字个数,空格个数,其他字符个数
代码实现
#include<stdio.h>
int main(void){
char c;
int letter = 0;
int space = 0;
int num = 0;
int other = 0;
while((c=getchar())!='\n'){
if((c>='a' && c<='z') || (c>='A' && c<='Z')){
letter++;
}
else if(c>='0' && c<='9'){
num++;
}
else if(c==' '){
space++;
}
else{
other++;
}
}
printf("字母=%d,数字=%d,空格=%d,其他=%d",letter,num,space,other);
return 0;
}
程序分析
(1)使用getchar函数接收输入的字符,遇到回车时结束接收字符
(2)(c>='a' && c<='z') || (c>='A' && c<='Z'),通过比较a到z字符范围判断是否属于字母
(3)(c>='0' && c<='9'),通过比较0到9的范围判断是否为数字
(4)(c==' '),判断是否为空格