2401_84143076 2024-04-12 20:06 采纳率: 50%
浏览 7
已结题

用指针引用函数统计字符个数(c语言)

需要通过指针变量调用函数统计一串字符中大小写字母和数字空格和其他字符的个数,存储个数的变量也为指针。该代码运行后无输出,请问问题在哪里

img

img

  • 写回答

4条回答 默认 最新

  • GISer Liu 2024-04-12 20:17
    关注

    该回答引用自GPT-3.5,由博主GISer Liu编写:

    首先,我们需要编写一个函数来统计字符中大小写字母、数字、空格和其他字符的个数,并将结果通过指针返回。接着,我们将传入的字符串逐个字符检查,根据字符的类型来增加相应的计数器。
    以下是解决方案的代码大纲:
    cCopy code

    #include <stdio.h>
    void countCharacters(const char *str, int *upper, int *lower, int *digit, int *space, int *other) {
    // 逐个遍历字符串中的字符
    while (*str != '\0') {
    if ((*str >= 'A' && *str <= 'Z')) {
    (*upper)++; // 大写字母计数器加一
    } else if ((*str >= 'a' && *str <= 'z')) {
    (*lower)++; // 小写字母计数器加一
    } else if ((*str >= '0' && *str <= '9')) {
    (*digit)++; // 数字计数器加一
    } else if (*str == ' ') {
    (*space)++; // 空格计数器加一
    } else {
    (*other)++; // 其他字符计数器加一
    }
    str++; // 移动到下一个字符
    }
    }
    int main() {
    char str[] = "Hello World 123 !@#"; // 测试字符串
    int upper = 0, lower = 0, digit = 0, space = 0, other = 0;
    // 调用函数统计字符个数
    countCharacters(str, &upper, &lower, &digit, &space, &other);
    // 输出统计结果
    printf("大写字母个数:%d\n", upper);
    printf("小写字母个数:%d\n", lower);
    printf("数字个数:%d\n", digit);
    printf("空格个数:%d\n", space);
    printf("其他字符个数:%d\n", other);
    return 0;
    }
    

    这段代码定义了一个函数countCharacters,它接受一个字符串指针和五个整型指针作为参数,分别用于存储大写字母、小写字母、数字、空格和其他字符的个数。在main函数中,我们声明了一个测试字符串,然后调用countCharacters函数进行统计,并输出结果。

    如果该回答解决了您的问题,请采纳!如果没有,请私信联系或评论您的疑惑

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

问题事件

  • 系统已结题 5月30日
  • 已采纳回答 5月22日
  • 创建了问题 4月12日