用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;
}
相关推荐
酱酱哥玩AI3 分钟前
Trae编译器:实现多目标班翠鸟优化算法(IPKO)无人机路径规划仿真(Python版),完整代码
算法
MPCTHU16 分钟前
二叉树、排序算法与结构图
数据结构·算法·排序算法
m0_5557629020 分钟前
struct 中在c++ 和c中用法区别
java·c语言·c++
亓才孓22 分钟前
[leetcode]树的操作
算法·leetcode·职场和发展
王禄DUT33 分钟前
化学方程式配平 第33次CCF-CSP计算机软件能力认证
开发语言·c++·算法
wuqingshun31415935 分钟前
蓝桥杯 XYZ
数据结构·c++·算法·职场和发展·蓝桥杯
DreamByte1 小时前
C++菜鸟教程 - 从入门到精通 第五节
开发语言·c++·算法
南玖yy1 小时前
数据结构C语言练习(两个队列实现栈)
c语言·数据结构·算法
明朝百晓生1 小时前
【强化学习】【1】【PyTorch】【强化学习简介优化框架】
算法
loser~曹1 小时前
基于快速排序解决 leetcode hot215 查找数组中第k大的数字
数据结构·算法·leetcode