You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言统计字母出现次数程序运行输出0或段错误问题求助

问题排查
  • 命令行参数索引错误:C语言中argv[0]固定存储程序自身名称,你需要统计的目标字符串对应argv[1],待匹配的字母对应argv[2],原代码遍历argv[0]、从argv[1]取匹配字符完全用错了数据源,因此输出结果错误。
  • 无参数合法性校验:如果用户传入参数数量不足,直接访问argv[1]、argv[2]会触发内存越界,也就是你遇到的段错误。
  • 未实现大小写不敏感匹配:原代码直接用==判断字符相等,大小写形式的同一字母会被判定为不匹配,不符合需求。
  • 输出格式不符合要求:原代码打印统计值时没有加换行符,和示例运行效果不符。
修正后代码
#include <stdio.h>
#include <ctype.h>

int rush2(int argc, char **argv)
{
    // 校验参数数量:程序名+目标字符串+待匹配字母,共3个参数
    if (argc != 3) {
        printf("参数错误,用法:%s 目标字符串 待匹配字母\n", argv[0]);
        return -1;
    }
    // 校验待匹配项是单个字母
    if (argv[2][1] != '\0') {
        printf("错误:请输入单个字母作为匹配项\n");
        return -1;
    }

    int i = 0;
    int count_letter = 0;
    // 统一转成小写实现不区分大小写匹配
    char target = tolower(argv[2][0]);

    while (argv[1][i] != '\0') {
        if (tolower(argv[1][i]) == target) {
            count_letter++;
        }
        i++;
    }
    printf("%d\n", count_letter);
    return count_letter;
}

int main (int ac, char **av)
{
    rush2(ac, av);
    return 0;
}
运行效果验证

执行命令:

./rush2 "Just because I don’t care doesn’t mean I don’t understand!" a

输出结果:

4

和需求示例完全一致。

内容的提问来源于stack exchange,提问作者Zibz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 15:06:03