Friday, 12 August 2016

Find all occurrences of pattern in a string

Find all occurrences of pattern(pat) in a a string(txt)


#include<stdio.h>
#include<string.h>
void main()
{
                char txt[30],  pat[30];
                int m, n;
                int i, j, found = 0;
                printf("\nEnter the main string:");
                gets(txt);
                printf("\nEnter the pattern to be searched: ");
                gets(pat);

                m = strlen(txt);
                n = strlen(pat);

                for(i=0;  i<=m-n;  i++)
                {
                                found  = 1;
                                for(j=0; j<n; j++)
                                {
                                                if(txt[i+j] != pat[j])
                                                {
                                                                found = 0;
                                                                break;
                                                }
                                }
                                if(found == 1)
                                                printf("\n The pattern found at index:%d",  i);
                }
                if(found  ==  0)
                                printf("\n   Pattern not found");
}

Output:
Enter the main string:    hello hii how hii
Enter the pattern to be searched:    hii

The pattern found at index:  6
The pattern found at index:   14

No comments:

Post a Comment