【问题标题】:Is there a way to search for an exact keyword in a file in C?有没有办法在 C 文件中搜索确切的关键字?
【发布时间】:2021-02-25 09:40:47
【问题描述】:

确切的关键字是指以单个单词表示的关键字,以空格字符开头和结尾(空格制表符换行)。我不想返回仅包含我的关键字作为子字符串的单词。

以下是我尝试从包含精确关键字的文本文件中查找和打印行。有没有更简单的方法?我当前的尝试不起作用,因为我不知道如何忽略包含我的关键字作为子字符串的行。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXLINESIZE 1024
#define MAXKEYWORD 256

int main()
{
  FILE* file = fopen("yankee.txt", "r");
  int linenumber =0;
  char keyword[MAXKEYWORD];
  char keywordline[MAXLINESIZE];

  while ((fscanf(file, "%[^\n]%*c", keywordline)) != EOF)
  {
      linenumber++;
      strcpy(keyword,"a");
      if(strstr(keywordline,keyword))
        {
          printf("linenumber = %d\n'%s'\n\n",linenumber,keywordline);
        }
  }
  return 0;
}

文本文件

Yankee Doodle went to town
riding on a pony
Stuck a feather in his cap
And called it macaroni.

所以,输出应该是:

linenumber = 2 
'riding on a pony'

linenumber = 3
'Stuck a feather in his cap'

【问题讨论】:

  • fscanf 可以读取“单词”,只需fscanf("%s"
  • 不相关:你不需要在循环内strcpy()。一次,在循环之外,就足够了。
  • 我建议您改用fgets 来阅读整行。然后像strtok 这样的东西来“标记”空间上的字符串。在循环中执行此操作,然后使用strcmp 查找“关键字”。

标签: c file whitespace keyword


【解决方案1】:

一种方法可能是运行strstr(),然后检查命中周围的字符是否为空格或任何算作单词分隔符的字符,或文本的开头/结尾。

类似:

char *p = strstr(text, key);
if (p) {
    if (p == text) {
        /* match at start of text */
        startok = 1;
    } else if (isspace(*(p-1)) {
        /* whitespace before the match */
        startok = 1;
    }
    /* same for end */
}

请确保检查您没有尝试读取字符串的开头/结尾。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-03
    • 1970-01-01
    • 1970-01-01
    • 2011-02-10
    • 2017-07-16
    • 1970-01-01
    相关资源
    最近更新 更多