在c中使用匹配一个确切的词

Matching an exact word using in c

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

如果

char* line = "hellodarkness my old friend";

我用

result = strstr(line, "hello");

result 将匹配(不是 NULL),但是我只想匹配确切的词 "hello"(这样 "hellodarkness" 就不会匹配)并且结果将为 NULL。 是否可以使用 strstr 来执行此操作,还是我必须使用 fscan 并逐字扫描行并检查匹配项?

我会:

  • 检查字符串是否在句子中
  • 如果在开头找到(与 line 相同的指针),添加单词的长度并检查是否找到字母数字字符。如果不是(或null-terminated),则匹配
  • 如果在其他地方找到,请添加额外的 "no alphanum before" 测试

代码:

#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;
}

此处不打印任何内容,但插入 punctuation/space before/after 或在 "hello" 之后终止字符串,您将获得匹配项。此外,在 hello.

之前插入字母数字字符 也不会获得匹配项

编辑:当只有 1 个 "hello" 但无法在 "hellohello hello" 中找到第二个 "hello" 时,上面的代码很好。所以我们要插入一个循环来寻找单词orNULL,每次都前进p,像这样:

#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;
}

既然strstr() returns指向你要识别的子串起始位置的指针,那么你可以用strlen(result)检查它是否是一个较长字符串的子串或您要查找的独立字符串。如果strlen(result) == strlen("hello"),则正确结束。如果它以 space 或标点符号(或其他分隔符)结尾,那么它也会在末尾被隔离。您还需要检查子字符串的开头是否在 "long string" 的开头,或者前面是否有空格、标点符号或其他分隔符。

这里有一个通用函数供您使用。它 returns 指向第一个匹配项的指针或 NULL 如果 none 可以找到:

#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;
}