用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;
}
相关推荐
小张成长计划..6 分钟前
【C++】25:哈希表的实现
数据结构·哈希算法·散列表
M--Y9 分钟前
Redis集群和典型应用场景
redis·算法·哈希算法·集群
zmj32032411 分钟前
单片机内存在C 语言编译后的 “逻辑分区”
c语言·单片机·内存分区
MediaTea16 分钟前
AI 术语通俗词典:召回率(分类)
人工智能·算法·机器学习·分类·数据挖掘
ECT-OS-JiuHuaShan16 分钟前
哲学的本质,是递归因果
java·开发语言·人工智能·科技·算法·机器学习·数学建模
米啦啦.17 分钟前
B-树,,
数据结构·b树·b-树
_深海凉_24 分钟前
LeetCode热题100-26. 删除有序数组中的重复项
python·算法·leetcode
shy^-^cky33 分钟前
文件的逻辑结构+ 物理结构
数据结构·操作系统·文件·数据·逻辑结构·物理结构·文件结构
w_com.h40 分钟前
C语言中 栈、队列、双向链表
c语言·开发语言·链表
睡觉就不困鸭42 分钟前
第14天 四数之和
数据结构·算法