用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;
}
相关推荐
南境十里·墨染春水21 分钟前
数据结构 —— 链表
数据结构·链表
为何创造硅基生物32 分钟前
C 语言 typedef 结构体私有化
c语言·开发语言·算法
yzx99101335 分钟前
递归算法入门:像俄罗斯套娃一样思考
人工智能·算法
心中有国也有家40 分钟前
从零上手 CANN 学习中心:像逛技术便利店一样学昇腾
学习·算法·开源
oo哦哦1 小时前
搜索矩阵系统的最短路密码:用Dijkstra算法和网络流理论,解释为什么你做了1000个关键词,流量还不如别人30个
网络·算法·矩阵
Matlab程序猿小助手1 小时前
【MATLAB源码-第319期】基于matlab的帝王蝶优化算法(MBO)无人机三维路径规划,输出做短路径图和适应度曲线.
开发语言·算法·matlab
图码1 小时前
二分查找进阶:如何在有序数组中快速找到Upper Bound?
数据结构·算法·面试·分类·柔性数组
试剂界的爱马仕1 小时前
《古董局·终局5:潮生》第 2 章:镜子的天赋
大数据·人工智能·算法
Cthy_hy1 小时前
树状数组(BIT)进阶:差分优化实现区间修改、区间查询
数据结构·python·算法
潜创微科技2 小时前
IT68353:双DP 1.4 + HDMI 2.0 + USB‑C 三合一转 HDMI 2.0 单芯片KVM切换方案
c语言·开发语言