用getchar()读取一串字符,分别统计字母、数字、空格、其他的个数
输入一串字符,分别统计字母、数字、空格、其他的个数 。◕ᴗ◕。
//输入一串字符,分别统计字母、数字、空格、其他的个数 。◕ᴗ◕。
//用getchar()循环获取字符串里每一个字符并判断
#include<stdio.h>
int main()
{
char c; //字符c
int bigLetter=0,smallLetter=0; //字母(大写和小写)
int number=0; //数字
int space=0; //空格
int other=0; //其他
printf("请输入一段字符串,将会分别统计这个字符串字母、数字、空格、其他(汉字占俩字节)的个数:\n\n------------------------------------\n\n");//格式
c = getchar(); //首次输入要判断的单字符
while(c != '\n') //判断字符是否为回车,不是则判断(循环),
{
if(( (c >= 'a') && (c <= 'z') )||((c >= 'A' )&&(c <= 'Z')) ){
if((c >= 'a') && (c <= 'z')){
smallLetter++; //小写
}else{
bigLetter++; //否则为大写
}
}else if((c >= '0') && (c <= '9')){
number++; //数字
}else if(c == ' '){
space++; //空格
}else{
other++; //其他
}
c = getchar(); //获取下一个字符,继续判断循环
}
printf("\n------------------------------------\n"); //格式
printf("\n此字符串中,一共有%d个,\n分别有:\n字母:%d个 (大写%d个,小写%d个)\n数字:%d个\n空格:%d个\n其他字符:%d个\n\n",bigLetter+smallLetter+number+space+other,bigLetter+smallLetter,bigLetter,smallLetter,number,space,other);
}
运行结果:
注意,这里用了英文状态下的感叹号和引号,中文状态下的感叹号和引号是占2个字节的!(中文状态下的感叹号和引号算作2个字符)
注意,这里用了英文状态下的感叹号和引号,中文状态下的感叹号和引号是占2个字节的!(中文状态下的感叹号和引号算作2个字符)
注意,这里用了英文状态下的感叹号和引号,中文状态下的感叹号和引号是占2个字节的!(中文状态下的感叹号和引号算作2个字符)