📜  C测验– 105 |问题2(1)

📅  最后修改于: 2023-12-03 15:30:15.210000             🧑  作者: Mango

C测验- 105 | 问题2

本题要求编写一个程序,连续输入某个字符并统计其中的英文字母、数字字符和其他字符的个数,直到输入的字符为’#’为止。

思路分析

本题要求统计输入字符中的英文字母、数字字符和其他字符的个数,可以采用循环输入字符,然后利用ASCII码判断每个字符的类型,最后输出各类字符的个数即可。

代码示例
#include <stdio.h>

int main()
{
    char ch;
    int letter = 0;
    int digit = 0;
    int others = 0;

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

    while((ch = getchar()) != '#')
    {
        if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
        {
            letter++;
        }
        else if(ch >= '0' && ch <= '9')
        {
            digit++;
        }
        else
        {
            others++;
        }
    }

    printf("字符中英文字母的个数为:%d\n", letter);
    printf("字符中数字字符的个数为:%d\n", digit);
    printf("字符中其他字符的个数为:%d\n", others);

    return 0;
}
代码说明

首先要定义3个变量letter、digit和others,分别用于统计输入字符中的英文字母、数字字符和其他字符的个数。

然后采用while循环输入字符,使用getchar()函数把输入的字符存入ch变量中,判断字符类型并统计各类字符的个数。

最后输出各类字符的个数即可。

最终效果

输入一段字符:

abc123!@#

输出结果:

字符中英文字母的个数为:3
字符中数字字符的个数为:3
字符中其他字符的个数为:2