コードは次のとおりです。キーワードをリスト内のタイトルと一致させるために使用strstr()
します。コードをテストする便宜上、title
フィールドのみを入力BookInfo
し、アイテムの数を 5 に制限しましlibrary
た。
#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