用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;
}
相关推荐
宋明炜5 分钟前
VSCode + MSYS2 配置 C 语言开发环境(详细步骤)
c语言·ide·vscode
唯道行7 分钟前
计算机图形学·25 消隐2 区域子分算法-光线投射算法
人工智能·算法·计算机视觉·计算机图形学·opengl
zfxwasaboy9 分钟前
BUG: failure at drivers/pci/msi.c:376/free_msi_irqs()!
linux·c语言·bug
jinxinyuuuus10 分钟前
FIRE之旅 财务计算器:实时交互式建模与前端性能工程
前端·人工智能·算法·自动化
千丈之松16 分钟前
能力和法律
算法
量子炒饭大师16 分钟前
Cyber骇客的脑机双链回流码 ——【初阶数据结构与算法】线性表之双向链表
数据结构·c++·链表
2401_8414956418 分钟前
【LeetCode刷题】缺失的第一个正数
数据结构·python·算法·leetcode·数组·哈希·缺失最小正整数
C++业余爱好者20 分钟前
Java 中的数据结构详解及应用场景
java·数据结构·python
小尧嵌入式27 分钟前
深入理解C/C++指针
java·c语言·开发语言·c++·qt·音视频
旧梦吟28 分钟前
脚本 生成图片水印
前端·数据库·算法·golang·html5