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

如何统计字符串中指定单词的出现次数?strstr仅匹配一次如何解决

问题原因

  1. 语法错误:存储字符串的变量应该声明为char*指针类型,而非单字符char类型
  2. 逻辑问题:strstr单次调用仅会返回第一个匹配子串的首地址,你仅调用了一次,所以计数只会加1
  3. 变量初始化遗漏:计数变量count未初始化,运行时可能拿到随机值,导致输出异常
  4. 匹配逻辑缺失:当前写法没有区分独立单词和子串,原示例中"This"包含的"is"也会被匹配,如果你要统计的是独立出现的"is",需要额外做边界判断

解决方法

每次匹配成功后,将指针移动到当前匹配子串的末尾,再次调用strstr遍历剩余字符串,直到返回NULL为止,可根据需求选择对应的实现方案:

方案1:统计所有子串匹配次数

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

int main() {
    char *buff = "This is a real-life, or this is just fantasy";
    char *op = "is";
    int count = 0;
    char *pos = buff;
    int op_len = strlen(op);
    
    // 循环查找直到没有匹配结果
    while((pos = strstr(pos, op)) != NULL) {
        count++;
        // 指针移动到当前匹配的末尾,避免重复匹配同一个位置
        pos += op_len;
    }
    printf("%d", count); // 输出结果为3,包含"This"里的"is"
    return 0;
}

方案2:仅统计独立单词的出现次数

如果需要排除子串匹配、只统计作为独立单词出现的目标内容,需要额外判断匹配位置前后是否为单词边界(空格、标点、字符串首尾等):

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

// 判断字符是否为单词边界
int is_word_boundary(char c) {
    return c == '\0' || isspace(c) || ispunct(c);
}

int main() {
    char *buff = "This is a real-life, or this is just fantasy";
    char *op = "is";
    int count = 0;
    char *pos = buff;
    int op_len = strlen(op);
    
    while((pos = strstr(pos, op)) != NULL) {
        // 校验匹配位置前后是否符合独立单词要求
        if((pos == buff || is_word_boundary(*(pos - 1))) 
            && is_word_boundary(*(pos + op_len))) {
            count++;
        }
        pos += op_len;
    }
    printf("%d", count); // 输出结果为2,符合你预期的独立"is"计数
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 13:06:05