用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;
}
相关推荐
大熊背7 分钟前
树莓派相机自动白平衡详解(二)
算法·白平衡·isppipeline
Scabbards_25 分钟前
面试Leetcode - 算法合集
算法·leetcode·面试
chuan.bai30 分钟前
Java RAG 实战附录:qwen3 与 bge-m3 模型切换指南
java·人工智能·算法
wuyk55531 分钟前
7.AVL 树:第一个自平衡二叉搜索树
开发语言·stm32·单片机·算法
rannn_11135 分钟前
【力扣hot100】二叉树专题+总结
java·算法·leetcode·二叉树
啊嘞嘞?37 分钟前
力扣(岛屿数量)
算法·leetcode
zander2581 小时前
LeetCode 198. 打家劫舍
算法·leetcode·深度优先
caimouse1 小时前
ReactOS 窗口系统架构分析
服务器·c语言
吃着火锅x唱着歌1 小时前
LeetCode 648.单词替换
算法·leetcode·职场和发展
caimouse1 小时前
ReactOS 图形系统分析(46):DC 工具 — dcutil.c
c语言·开发语言