gpt4 book ai didi

c - 匹配在 c 中使用的确切单词

转载 作者:行者123 更新时间:2023-12-04 12:31:31 25 4
gpt4 key购买 nike

我可以使用 strstr 函数来匹配精确的单词吗?例如,假设我有单词 hello , 和一个输入字符串 line :

如果

char* line = "hellodarkness my old friend";

我用
result = strstr(line, "hello");
result将匹配(不为 NULL),但是我只想匹配确切的单词“hello”(这样“hellodarkness”将不匹配)并且结果将为 NULL。
是否可以使用 strstr 来做到这一点?还是我必须使用 fscan并逐字扫描行并检查匹配项?

最佳答案

这是用于您目的的通用函数。它返回一个指向第一个匹配项或 NULL 的指针。如果找不到:

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

char *word_find(const char *str, const char *word) {
const char *p = NULL;
size_t len = strlen(word);

if (len > 0) {
for (p = str; (p = strstr(p, word)) != NULL; p++) {
if (p == str || !isalnum((unsigned char)p[-1])) {
if (!isalnum((unsigned char)p[len]))
break; /* we have a match! */
p += len; /* next match is at least len+1 bytes away */
}
}
}
return p;
}

关于c - 匹配在 c 中使用的确切单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42352846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com