【问题标题】:how to implement a search in an array containing book names in c如何在c中包含书名的数组中实现搜索
【发布时间】:2013-05-07 05:53:14
【问题描述】:

我有这个结构数组

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

我看到了使用 int 而不是使用 char 数据类型的线性搜索,这是如何处理的

【问题讨论】:

    标签: c search struct char


    【解决方案1】:

    这里是代码。它使用strstr()来匹配关键字与列表中的标题。为了方便测试代码,我只有BookInfo中的title字段,并且我限制了项目的数量在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
    

    【讨论】:

    • @Tata​​n1 我也试过了,效果很好,我也在添加输出。等等。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2021-12-02
      • 1970-01-01
      • 2020-05-21
      • 2020-11-03
      • 1970-01-01
      • 2011-09-01
      • 2012-09-07
      • 2021-01-21
      • 1970-01-01
      相关资源
      最近更新 更多