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

C语言如何判断指定完整单词是否存在于给定句子中

C语言判断完整单词是否存在于句子中的实现方案

核心判定逻辑

完整单词匹配需要同时满足三个边界条件:

  • 匹配到的子串长度和目标单词长度完全一致
  • 子串的前一个字符要么是字符串起始位置,要么是空白字符(空格、制表符、换行符等)
  • 子串的后一个字符要么是字符串结束符\0,要么是空白字符

实现代码

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

int is_full_word_exist(const char *sentence, const char *target_word) {
    // 边界校验:输入为空直接返回0
    if (sentence == NULL || target_word == NULL || *target_word == '\0') {
        return 0;
    }
    int word_len = strlen(target_word);
    const char *cur_pos = sentence;
    const char *match_pos;

    while ((match_pos = strstr(cur_pos, target_word)) != NULL) {
        // 检查前边界
        int prefix_ok = (match_pos == sentence) || isspace((unsigned char)*(match_pos - 1));
        // 检查后边界
        int suffix_ok = (*(match_pos + word_len) == '\0') || isspace((unsigned char)*(match_pos + word_len));
        
        if (prefix_ok && suffix_ok) {
            return 1;
        }
        // 当前匹配不满足完整单词,向后偏移继续查找
        cur_pos = match_pos + 1;
    }
    // 没有找到任何匹配的完整单词
    return 0;
}

// 测试用例
int main() {
    const char *str = "I have a meeting";
    printf("匹配\"meet\"结果:%d\n", is_full_word_exist(str, "meet"));
    printf("匹配\"meeting\"结果:%d\n", is_full_word_exist(str, "meeting"));
    printf("匹配\"I\"结果:%d\n", is_full_word_exist(str, "I"));
    printf("匹配\"have\"结果:%d\n", is_full_word_exist(str, "have"));
    return 0;
}

输出结果

匹配"meet"结果:0
匹配"meeting"结果:1
匹配"I"结果:1
匹配"have"结果:1

注意事项

  • 用isspace函数判断空白字符,可兼容空格、制表符\t、换行符\n等多种空白分隔场景
  • 单次匹配不满足条件时,需要将查找起始位置向后偏移1位,避免漏过重叠场景的匹配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 15:54:03