Tuesday 10 July 2012

WAP to find the position of a given word in a given text


#include<stdio.h>
#include<string.h>
int main()
{
    char S[100],W[20];
    int i,j,l,m,flage=0;
    printf("Enter Text : ");
    gets(S);
    printf("\nEnter Word : ");
    gets(W);
    l=strlen(S);
    m=strlen(W);
    for(i=0;i<l;i++)
    {
        if(S[i]==W[0])
        {
            for(j=1;j<m;j++)
            {
                if(S[i+j]!=W[j])
                    break ;
            }
            if(j==m)
            {
                if(!flage)
                    printf("\nPosition : ");
                flage =1;
                printf(" %d",i);
                //flage=
            }
        }
    }
    if(!flage)
        printf("\nNot found \n");
return 0;
}
Let me know your thoughts.

1 comment:

  1. It would be better to implement KMP instead of your O(length of text * length of word) algorithm... :)

    ReplyDelete