C语言 统计字符类型个数

这个程序读取用户输入的一行字符,并统计其中的英文字母、空格、数字和其他字符的个数。

#include <stdio.h>
#include <ctype.h>

int main() {
    char ch;
    int letters = 0, spaces = 0, digits = 0, others = 0;
    printf("输入一行字符: ");
    
    // 逐字符读取输入,直到遇到换行符 '\n'
    while ((ch = getchar()) != '\n') {
        if (isalpha(ch))
            letters++;
        else if (isspace(ch))
            spaces++;
        else if (isdigit(ch))
            digits++;
        else
            others++;
    }
    
    printf("字母个数: %d\n", letters);
    printf("空格个数: %d\n", spaces);
    printf("数字个数: %d\n", digits);
    printf("其他字符个数: %d\n", others);
    return 0;
}

代码说明

  1. isalpha 函数用于判断字符是否是英文字母。
  2. isspace 函数用于判断字符是否是空格。
  3. isdigit 函数用于判断字符是否是数字。
  4. 程序使用 getchar 函数逐字符读取输入,并根据字符类型计数。
在C语言中,要统计字符类型个数,通常会统计字母、数字、空格和其他字符的数量。可以通过遍历输入的字符串,使用`ctype.h`头文件中的函数来判断字符的类型。 以下是实现该功能的示例代码: ```c #include <stdio.h> #include <ctype.h> int main() { char input[1000]; int letters = 0, digits = 0, spaces = 0, others = 0; // 提示用户输入字符串 printf("请输入一个字符: "); fgets(input, sizeof(input), stdin); // 遍历字符串 for (int i = 0; input[i] != '\0'; i++) { if (isalpha(input[i])) { letters++; } else if (isdigit(input[i])) { digits++; } else if (isspace(input[i])) { spaces++; } else { others++; } } // 输出统计结果 printf("字母的数量: %d\n", letters); printf("数字的数量: %d\n", digits); printf("空格的数量: %d\n", spaces); printf("其他字符的数量: %d\n", others); return 0; } ``` ### 代码解释 1. **头文件包含**:包含了`stdio.h`用于输入输出操作,`ctype.h`用于字符类型判断。 2. **变量声明**:定义了一个字符数组`input`用于存储用户输入的字符串,以及四个整型变量`letters`、`digits`、`spaces`和`others`分别用于统计字母、数字、空格和其他字符的数量。 3. **用户输入**:使用`fgets`函数从标准输入读取用户输入的字符串。 4. **字符类型判断**:使用`for`循环遍历字符串,通过`isalpha`、`isdigit`和`isspace`函数分别判断字符是否为字母、数字和空格,根据判断结果更新相应的计数器。 5. **输出结果**:输出统计得到的各类字符的数量。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值