Interviews Questions, Algorithms, Aptitude, C Interview Program, C Theory Question, Aptitude Tricks, Test Series,

Showing posts with label Naive String Matching. Show all posts
Showing posts with label Naive String Matching. Show all posts

Wednesday, 27 March 2019

NAIVE STRING MATCHING Algorithm

Algorithm: NAÏVE_STRING_MATCHER (T, P)

n ← length [T]
m ← length [P]
for s ← 0 to - m do
    if P[1 . . m] = T[+1 . . + 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