用C语言编写一个函数

输出给定的字符串中字母、数字、空格和其他字符的个数

(1)编写main函数

复制代码
#include <stdio.h>

int main() {
    

    return 0;
}

(2)编写计数函数

复制代码
#include <stdio.h>

void count_chars(char *str) {
    int letters = 0; // 字母计数器
    int digits = 0; // 数字计数器
    int spaces = 0; // 空格计数器
    int others = 0; // 其他字符计数器

    // 判断并计数
    for (int i = 0; str[i] != '\0'; ++i) {
        if ((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z')) {
            letters++;
        } else if (str[i] >= '0' && str[i] <= '9') {
            digits++;
        } else if (str[i] == ' ') {
            spaces++;
        } else {
            others++;
        }
    }

    // 输出各种字符的个数
    printf("Letters:%d\n", letters);
    printf("Digits:%d\n", digits);
    printf("Spaces:%d\n", spaces);
    printf("Others:%d\n", others);
}

int main() {


    return 0;
}

(3)编写main函数

复制代码
#include <stdio.h>

void count_chars(char *str) {
    int letters = 0; // 字母计数器
    int digits = 0; // 数字计数器
    int spaces = 0; // 空格计数器
    int others = 0; // 其他字符计数器

    // 判断并计数
    for (int i = 0; str[i] != '\0'; ++i) {
        if ((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z')) {
            letters++;
        } else if (str[i] >= '0' && str[i] <= '9') {
            digits++;
        } else if (str[i] == ' ') {
            spaces++;
        } else {
            others++;
        }
    }

    // 输出各种字符的个数
    printf("Letters:%d\n", letters);
    printf("Digits:%d\n", digits);
    printf("Spaces:%d\n", spaces);
    printf("Others:%d\n", others);
}

int main() {
    char str[30];
    printf("Please enter the value of str: ");
    fgets(str, sizeof(str), stdin); // 使用 fgets 读取整行输入
    count_chars(str);

    return 0;
}
相关推荐
忍者必须死14 分钟前
JDK1.7的HashMap的环形链表
java·数据结构·算法·链表
NEXT0617 分钟前
数组转树与树转数组
前端·数据结构·面试
仟濹19 分钟前
【算法打卡day10(2026-02-24 周二)动态规划DP基础理论】
算法·动态规划
小刘爱玩单片机23 分钟前
【stm32协议外设篇】- HX1838 红外接收头
c语言·stm32·单片机·嵌入式硬件
xiaoccii24 分钟前
C++(入门版)
java·c++·算法
ADDDDDD_Trouvaille26 分钟前
2026.2.23——OJ101-103题
c++·算法
月挽清风26 分钟前
代码随想录第34天:动态规划
算法·动态规划
HCl__盐酸28 分钟前
题解:Kitamasa 算法板子
算法
筱昕~呀30 分钟前
冲刺蓝桥杯-DFS板块(第一天)
算法·蓝桥杯·深度优先
小刘爱玩单片机31 分钟前
【stm32协议外设篇】- DS18B20 单总线数字温度检测模块
c语言·stm32·单片机·嵌入式硬件