题目描述
本题要求编写程序,输入N个字符,统计其中英文字母、空格或回车、数字字符和其他字符的个数。
输入格式:
输入:
在第一行中给出正整数N,第二行输入N个字符,最后一个回车表示输入结束,不算在内。
输出:
letter = 英文字母个数, blank = 空格或回车个数, digit = 数字字符个数, other = 其他字符个数
解题思路
思路非常简单,但是要注意一定要读走换行符。否则将会少读入一个字符。
代码实现
#include <stdio.h>
int main()
{
int n;
scanf("%d", &n);
int letter=0, blank=0, digit=0, other=0;
getchar(); // 注意读走空格 非常重要
while (n > 0){
char ch = getchar();
if ((ch>='a'&& ch<='z') || (ch>='A'&&ch<='Z'))
letter++;
else if (ch == ' ' || ch == '\n')
blank++;
else if (ch>='0' && ch<='9')
digit++;
else
other++;
n--;
}
printf("letter = %d, blank = %d, "
"digit = %d, other = %d\n", letter, blank, digit, other);
return 0;
}