这是代码。它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