用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;
}
相关推荐
是小Y啦12 分钟前
leetcode 739.每日温度
java·算法·leetcode
aa.173580338 分钟前
剖析淘宝猫粮前五十店铺:销售策略、产品特点与用户偏好
开发语言·python·算法·数据挖掘
水之魂20181 小时前
leetcode哈希表(二)-两个数组的交集
算法·leetcode·散列表
Bug退退退1231 小时前
LeetCode18.四数之和
java·数据结构·算法
EQUINOX11 小时前
LeetCode 第141场双周赛个人题解
算法·leetcode·职场和发展
九圣残炎1 小时前
【从零开始的LeetCode-算法】3200. 三角形的最大高度
java·算法·leetcode
长潇若雪1 小时前
扫雷(C 语言)
c语言·开发语言·经验分享
一个不喜欢and不会代码的码农1 小时前
设计一个尽可能高效的划分算法,满足|n1-n2|最小且|S1-S2|最大
数据结构·算法·排序算法
ImAlex1 小时前
【OpenCV】OpenCV指南:图像处理基础及实例演示
算法
CharlesC++2 小时前
一元n次多项式加法【数据结构-链表】
数据结构·链表