0

我有这个结构数组

struct BookInfo
{
    char title[50];
    int numAuthors;
    char authors[50][50];
    int year;
    int checkedout;
};

struct BookInfo library[500];

我试图弄清楚如何实现搜索,用户可以在其中输入一个单词,并且该函数将打印该书的全名,例如在两本书的 char 标题中

a rose for emily
war of the worlds

如果用户输入 worlds 函数将打印

war of the worlds

我如何看待这个我看到了使用整数而不是字符数据类型的线性搜索

4

2 回答 2

0

这是代码。它strstr()用于将关键字与列表中的标题匹配。为了方便测试代码,我只有title字段,BookInfo我将项目数限制library为5。

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

struct BookInfo
{
    char title[50];
};

struct BookInfo library[5];

int main()
{
    int i,j=0;
    char keyword[50];

//Getting the titles of books from librarian

    for(i=0; i<5; i++)
    {
        printf("Enter book no.%d ",i+1);
        gets(library[i].title);
    }
 // Search based on keyword

    printf("Enter the title keyword to search\n");
    gets(keyword);
    for(i=0; i<5; i++)
    {
        if(strstr(library[i].title,keyword)==NULL)
            j++;

        else
            printf("Book to have the  word %s in title is %s\n",keyword,library[i].title);

    }
    if(j==0)
        printf("No book with given title/keyword");
}

输出

Enter book no.1 The importance of religion

Enter book no.2 Why sex sells

Enter book no.3 Origin of species

Enter book no.4 Are you obsessed with sex?

Enter book no.5 Why are programmers sexy

Enter the title keyword to search sex

Book to have the  word sex in title is Why sex sells

Book to have the  word sex in title is Are you obsessed with sex?

Book to have the  word sex in title is Why are programmers sexy
于 2013-05-07T06:26:12.463 回答
0

有几种方法可以实现它。但是,对我来说,实现这一点的最佳便捷方式是使用“Trie” http://en.wikipedia.org/wiki/Trie。使用 trie 可以帮助您以非常有效的方式实现这一点。

于 2013-05-07T06:20:40.800 回答