Algorithm: NAÏVE_STRING_MATCHER (T, P)
n ← length [T]
m ← length [P]
for s ← 0 to n - m do
if P[1 . . m] = T[s +1 . . s + m]
then return valid shift s
n ← length [T]
m ← length [P]
for s ← 0 to n - m do
if P[1 . . m] = T[s +1 . . s + m]
then return valid shift s
C program:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
main()
{
char p[50],t[50];
int i,j,n,m,flag=-1;
printf("enter the main string \n");
scanf("%s",t);
printf("enter the pattern \n");
scanf("%s",p);
n=strlen(t);
m=strlen(p);
for(i=0;i<=n-m;i++)
{
j=0;
while(j<m && p[j]==t[i+j])
{
j++;
}
if(j==m)
{
flag=0;
printf("string is found at %d\n",i);
}
}
if(flag!=0)
printf("string not found \n");
}
Output:
enter the main string
qwertykeypadkeyboard
enter the pattern
key
string is found at 6
string is found at 12
0 comments:
Post a Comment