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

C语言统计字符串单词、大小写、数字、空格的程序错误排查求助

代码错误汇总
  • 范围判断逻辑错误
    判断小写、大写、数字时使用了>和<,没有包含边界值,导致a/z、A/Z、0/9这些字符不会被统计到对应分类中,这就是大写、小写字符数统计不对的原因,应该改为>=和<=。
  • 单词统计行存在语法错误
    else if (str[i] == ' ' && str[i + 1] != ' ');末尾多写了一个分号,导致这个条件判断完全失效,后面的words++会在每轮循环都执行一次,所以单词数完全不符合预期。
  • 单词统计逻辑错误
    你原本的空格数+1仅适用于无首尾空格、无连续空格的场景,无法处理通用情况。正确的单词统计逻辑应该增加状态标记,判断当前是否处于单词内部,仅在从非单词状态(空格)切换到单词状态时计数。
  • 函数使用风险
    gets()函数已经被C标准废弃,存在缓冲区溢出漏洞,建议替换为fgets()。
修正后代码
#include <stdio.h>
// 引入ctype.h使用内置字符判断函数,比手动写范围更严谨
#include <ctype.h>

int main() {
    char str[1001];
    int words = 0;
    int numbers = 0;
    int uppercharacters = 0;
    int lowercharacters = 0;
    int spaces = 0;
    int in_word = 0; // 状态标记:0=当前不在单词中,1=当前在单词中
    int i;

    printf("Please enter the string of characters: ");
    // 替换不安全的gets为fgets
    fgets(str, sizeof(str), stdin);
    
    for (i = 0; str[i] != '\0'; i++) {
        if (islower(str[i])) {
            lowercharacters++;
            // 从非单词状态进入单词状态,单词数+1
            if (!in_word) {
                words++;
                in_word = 1;
            }
        } else if (isupper(str[i])) {
            uppercharacters++;
            if (!in_word) {
                words++;
                in_word = 1;
            }
        } else if (str[i] == ' ') {
            spaces++;
            in_word = 0;
        } else if (isdigit(str[i])) {
            numbers++;
            if (!in_word) {
                words++;
                in_word = 1;
            }
        }
        // 其他特殊符号默认视为单词分隔符,可根据需求调整逻辑
        else {
            in_word = 0;
        }
    }

    printf("Spaces = %d\n", spaces);
    printf("numbers = %d\n", numbers);
    printf("Upper Case characters = %d\n", uppercharacters);
    printf("Lower Case characters = %d\n", lowercharacters);
    printf("Words = %d\n", words);
    return 0;
}

如果不想使用ctype.h的内置函数,把对应的字符判断条件替换为str[i] >= 'a' && str[i] <= 'z'这类手动范围判断即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 08:09:00