搜索 EXACT 字符串中的空格来自C程序的txt文件

问题描述

struct Book {
        char *title;
        char *authors; 
        unsigned int year; 
        unsigned int copies; 
};


int existance_of_book(char title[])
{
    char string[30];
    ptr_to_library = fopen("library.txt","r");

  if(ptr_to_library == NULL)
  {
    printf("\nERROR: cannot open file\n");
    return -1;
  }

    while (fgets(title,sizeof(title),ptr_to_library) != NULL)
  {
    if(strstr(string,title)!=0)
    {
      printf("book found\n");
      return 1;
    }
  }
    return 0;
}

我正在尝试在文件搜索字符串,但由于我要搜索的字符串中有空格,因此该函数无法找到该字符串。例如,如果 .txt 文件中的字符串为“hello”,而在函数中输入的字符串为“he”,则此函数也会找到匹配项。即使有空格,有没有办法在文件搜索确切的字符串

解决方法

使用 strstr 查找子字符串。
检查子字符串是否位于行首或前面有标点符号或空格。
还要检查子字符串是否位于行尾或以标点符号或空格结尾。
如果使用 fgets 获取要查找的子字符串,请务必使用 strcspn 删除尾随的换行符。在文件的行中,尾部的换行符应该无关紧要,但此代码使用 strcspn 将其删除。

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

#define SIZE 1024

int main ( void) {
    char find[SIZE] = "he";
    char line[SIZE] = "";
    char const *filename = "library.txt";
    char *match = NULL;
    FILE *pf = NULL;

    if ( NULL == ( pf = fopen ( filename,"r"))) {
        perror ( filename);
        exit ( EXIT_FAILURE);
    }

    int length = strlen ( find);

    while ( fgets ( line,SIZE,pf)) {//read lines until end of file
        line[strcspn ( line,"\n")] = 0;//remove newline
        char *temp = line;
        while ( ( match = strstr ( temp,find))) {//look for matches
            if ( match == line //first of line
            || ispunct ( (unsigned char)*(match - 1))
            || isspace ( (unsigned char)*(match - 1))) {
                if ( 0 == *(match + length)//end of line
                || ispunct ( (unsigned char)*(match + length))
                || isspace ( (unsigned char)*(match + length))) {
                    printf ( "found %s in %s\n",find,line);
                    break;//found a match
                }
            }
            temp = match + 1;//advance temp and check again for matches.
        }
    }

    fclose ( pf);

    return 0;
}