Saturday 9 January 2016

Find The Location of Sub-string (Algorithm 3.3)


Before seeing the solution make sure that you tried enough. Don’t paste the whole code, just find out the logic. If you stuck in trouble, just inform me on comment.

/**Bismillahir Rahmanir Rahim.**/

#include <stdio.h>
#include <string.h>
int main()
{
    char t[1000], p[1000];
    int k, r, s, Index = -1, max, l, m, cnt;
    printf("Please, Input string.\n");
    s = strlen(gets(t));
    printf("Please, Input Sub-string.\n");
    r = strlen(gets(p));
    max = s-r+1;
    for(k=0; k<max; k++)
    {
        if(t[k]==p[0])
        {
            for(l=1, cnt=1, m=k+1; l<r; l++, m++)
            {
                if(p[l]==t[m])
                    cnt++;
                else break;
            }
            if(cnt==r)
            {
                Index = k;
                printf("INDEX = %d\n", Index);
                k+=(r-1);
            }
        }
    }
    if(Index==-1) printf("There is no matching\n");
    return 0;
}

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.