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

C语言程序开发需求:实现元音辅音统计及单词出现次数查询

C语言字符串统计与单词查询程序补全

功能补全说明

  • 新增单词总数统计:基于空格/非字母字符分隔逻辑计数,自动忽略连续空格
  • 新增单词精准查询:支持输入目标单词,统计其在原字符串中的完整出现次数

完整实现代码

#include <stdio.h>
#include <string.h>
#include <ctype.h>

// 判断是否为元音字母(不区分大小写)
int isVowel(char c) {
    c = tolower(c);
    return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
}

// 判断是否为辅音字母(字母且非元音,不区分大小写)
int isConsonant(char c) {
    c = tolower(c);
    return (c >= 'a' && c <= 'z') && !isVowel(c);
}

// 统计字符串中的单词总数
int countWords(const char *str) {
    int count = 0;
    int inWord = 0; // 标记当前是否处于单词内部

    while (*str != '\0') {
        if (isspace(*str)) {
            inWord = 0;
        } else if (!inWord) {
            inWord = 1;
            count++;
        }
        str++;
    }
    return count;
}

// 统计目标单词在字符串中的完整出现次数
int countWordOccurrences(const char *str, const char *target) {
    int count = 0;
    size_t targetLen = strlen(target);
    if (targetLen == 0) return 0;

    while (*str != '\0') {
        // 跳过非字母数字的分隔符,定位到单词起始
        while (*str != '\0' && !isalnum(*str)) {
            str++;
        }
        // 匹配目标单词
        if (strncmp(str, target, targetLen) == 0) {
            // 验证匹配的是完整单词(后续为分隔符或字符串结尾)
            char nextChar = *(str + targetLen);
            if (nextChar == '\0' || !isalnum(nextChar)) {
                count++;
            }
        }
        str++;
    }
    return count;
}

int main() {
    char inputStr[1000];
    char queryWord[100];
    int vowels = 0, consonants = 0, words = 0;

    // 读取输入字符串
    printf("请输入一段字符串:");
    fgets(inputStr, sizeof(inputStr), stdin);
    inputStr[strcspn(inputStr, "\n")] = '\0'; // 移除换行符

    // 统计元音与辅音
    for (int i = 0; inputStr[i] != '\0'; i++) {
        if (isVowel(inputStr[i])) {
            vowels++;
        } else if (isConsonant(inputStr[i])) {
            consonants++;
        }
    }

    // 统计单词总数
    words = countWords(inputStr);

    // 输出统计结果
    printf("\n统计结果:\n");
    printf("元音字母数量:%d\n", vowels);
    printf("辅音字母数量:%d\n", consonants);
    printf("单词总数:%d\n", words);

    // 单词查询流程
    printf("\n请输入要查询的单词:");
    fgets(queryWord, sizeof(queryWord), stdin);
    queryWord[strcspn(queryWord, "\n")] = '\0';

    int occurrences = countWordOccurrences(inputStr, queryWord);
    printf("单词 \"%s\" 在字符串中出现了 %d 次\n", queryWord, occurrences);

    return 0;
}

关键逻辑解析

  • 单词计数:countWords通过inWord状态标记,仅在从非单词状态切换到单词状态时计数,避免连续空格或标点导致的重复统计。
  • 精准单词匹配:countWordOccurrences先跳过分隔符,再用strncmp匹配目标,同时检查匹配后的字符是否为非字母数字,确保统计的是完整单词(比如不会把"cat"统计到"category"中)。
  • 大小写兼容:所有字符判断前通过tolower统一转换为小写,保证统计不受输入大小写影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 09:16:14