首页 > 编程笔记

C语言统计英文字母、空格、数字和其它字符的个数

编写程序,要求输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。

分析

利用循环结构 while 或者 for,逐个判断输入字符的值:
若以上三种情况都不是,那么当前字符属于其它字符的范畴。

实现

#include <stdio.h>

int main() {
    char c;           //用户输入的字符
    int letters = 0;// 字母数目
    int space = 0;    // 空格数目
    int digit = 0;   // 整数数目
    int others = 0;   // 其他字符数目

    printf("输入一些字符:");
    while ((c = getchar()) != '\n') {  // 每次读取一个字符,回车时结束
        if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')
            letters++;
        else if (c == ' ')
            space++;
        else if (c >= '0' && c <= '9')
            digit++;
        else
            others++;
    }

    printf("\n统计结果:\n英文字母=%d\n空格=%d\n整数=%d\n其他字符=%d\n\n", letters, space, digit, others);

    return 0;
}
运行结果:

输入一些字符:http://c.biancheng.net/ 12345

统计结果:
英文字母=17
空格=1
整数=5
其他字符=6

优秀文章

添加微信咨询 扫码添加管理员微信 扫码添加管理员微信
微信ID:biancheng_yan