Saturday, 14 September 2013

Search/Find Function To Find A String

This program assigns a structure with some random things we may find in a guy's den. Then we can enter a string. The program performs a search & find. If the string is found within the "Name" strings, it is displayed with the serial number.
This program uses strstr() to search for the user entered string among the already defined strings.

Sample:



Code:

#include <stdio.h>
#include <strings.h>

void find_item(char find_me[]);

struct items
{
    int slno;
    char name[40];
};
struct items a[10];

int main()
{
    int i;
    char input1[80];

    for(i=0;i<10;i++)
    {
        a[i].slno=i+1;
        switch(i)
        {
        case 0:
            strcpy(a[i].name,"Table");
            break;
        case 1:
            strcpy(a[i].name,"Chair");
            break;
        case 2:
            strcpy(a[i].name,"Whiskey");
            break;
        case 3:
            strcpy(a[i].name,"iPad");
            break;
        case 4:
            strcpy(a[i].name,"Home Gym");
            break;
        case 5:
            strcpy(a[i].name,"Guitar");
            break;
        case 6:
            strcpy(a[i].name,"Bill Reciepts");
            break;
        case 7:
            strcpy(a[i].name,"Watch");
            break;
        case 8:
            strcpy(a[i].name,"Sun-glasses");
            break;
        case 9:
            strcpy(a[i].name,"Cell Phone");
            break;
        }
    }

    while(1)
    {
        system("cls");
        printf("Find what? (END to end): ");
        fscanf(stdin,"%79s",input1);
        i=strcmp(input1,"END"); //if the user input END, i will recieve Zero as a return value.
        if(i==0)
        {
            exit(0);
        }
        find_item(input1);
    }
    return 0;
}

void find_item(char find_me[])
{
    int i,x=1;
    for(i=0;i<10;i++)
    {
        if(strstr(a[i].name,find_me)) //if the comparision turns up a result
        {
            printf("SlNo. %i %s\n",i+1,a[i].name);
            x=0;
        }
    }
    if(x==1)
    {
        printf("Not Found.");
    }
    getch();
}

No comments:

Post a Comment