问题描述
我可以使用strstr函数匹配确切的单词吗?例如,假设我有一个单词hello
和一个输入字符串line
:
Can I use the strstr function to match exact word? For example, let's say I have the word hello
, and an input string line
:
如果
char* line = "hellodarkness my old friend";
我用
result = strstr(line, "hello");
result
将匹配(不是NULL),但是我只想匹配精确的单词"hello"(这样"hellodarkness"将不匹配),结果将为NULL.是否可以使用strstr
来执行此操作,还是我必须使用fscan
并逐字扫描行并检查是否匹配?
result
will match (be not NULL), however I want to match only the exact word "hello" (so that "hellodarkness" would not match) and result will be NULL.Is it possible to do this using strstr
or do I have to use fscan
and scan the line word by word and check for matches?
推荐答案
我会:
- 检查字符串是否在句子中
- 如果在开始时找到(与
line
相同的指针),则添加单词的长度并检查是否找到了字母数字字符.如果不是(或以空值结尾),则匹配 - 如果在其他任何地方找到,请添加额外的之前没有字母数字"测试
- check if string is in sentence
- if found at start (same pointer as
line
), add the length of the word and check if alphanumerical char found. If not (or null-terminated), then match - if found anywhere else, add the extra "no alphanum before" test
代码:
#include <stdio.h>
#include <strings.h>
#include <ctype.h>
int main()
{
const char* line = "hellodarkness my old friend";
const char *word_to_find = "hello";
char* p = strstr(line,word_to_find);
if ((p==line) || (p!=NULL && !isalnum((unsigned char)p[-1])))
{
p += strlen(word_to_find);
if (!isalnum((unsigned char)*p))
{
printf("Match\n");
}
}
return 0;
}
在这里它什么也不会打印,但是在"hello"
之前/之后插入一个标点符号/空格,或者在"hello"
之后终止该字符串,您将得到一个匹配项.另外,您将无法通过在之前插入字母数字字符打招呼.
here it doesn't print anything, but insert a punctuation/space before/after or terminate the string after "hello"
and you'll get a match. Also, you won't get a match by inserting alphanum chars before hello.
只有1个"hello"
时,上面的代码很好,但是在"hellohello hello"
中找不到第二个"hello"
.因此,我们必须插入一个循环来查找单词或NULL
,每次都使p
前进,如下所示:
the above code is nice when there's only 1 "hello"
but fails to find the second "hello"
in "hellohello hello"
. So we have to insert a loop to look for the word or NULL
, advancing p
each time, like this:
#include <stdio.h>
#include <strings.h>
#include <ctype.h>
int main()
{
const char* line = " hellohello hello darkness my old friend";
const char *word_to_find = "hello";
const char* p = line;
for(;;)
{
p = strstr(p,word_to_find);
if (p == NULL) break;
if ((p==line) || !isalnum((unsigned char)p[-1]))
{
p += strlen(word_to_find);
if (!isalnum((unsigned char)*p))
{
printf("Match\n");
break; // found, quit
}
}
// substring was found, but no word match, move by 1 char and retry
p+=1;
}
return 0;
}
这篇关于在c中使用匹配精确词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!