簡體   English   中英

從 C 程序中搜索帶有空格的 EXACT 字符串

[英]searching for EXACT string with spaces in . txt file from C program

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

我正在嘗試在文件中搜索字符串,但由於我要搜索的字符串中有一個空格,因此 function 無法找到該字符串。 此 function 也會找到匹配項,例如,如果 .txt 文件中的字符串讀取“hello”,並且 function 中輸入的字符串是“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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM