You are on page 1of 5

Write a program to implement the first pattern

matching algorithm.

#include <stdio.h>
#include <string.h>
int match(char [], char []);
int main() {
char a[100], b[100];
int position;
printf("Enter some text\n");
gets(a);
printf("Enter a string to find\n");
gets(b);
position = match(a, b);
if (position != -1) {
printf("Found at location: %d\n", position + 1);
}
else {
printf("Not found.\n");
}
return 0;
}
int match(char text[], char pattern[]) {
int c, d, e, text_length, pattern_length, position = -1;
text_length = strlen(text);
pattern_length = strlen(pattern);
if (pattern_length > text_length) {
return -1;
}
for (c = 0; c <= text_length - pattern_length; c++) {
position = e = c;
for (d = 0; d < pattern_length; d++) {
if (pattern[d] == text[e]) {
e++;
}
else {
break;
}
}
if (d == pattern_length) {
return position;
}
}
return -1;
}

Output:
Write a program to implement the second pattern
matching algorithm.

#include<stdio.h>
#include<conio.h>
#include<string.h>
char F(char,char);
int state[4][3];
void main()
{
char P[80]= {"aaaa"};
char T[80] = {"aaaabaca"};
int N,K,S,I,INDEX;

state[0][0] = 1;
state[0][1] = 0;
state[0][2] = 0;
state[1][0] = 2;
state[1][1] = 0;
state[1][2] = 0;
state[2][0] = 2;
state[2][1] = 3;
state[2][2] = 0;
state[3][0] = -1;
state[3][1] = 0;
state[3][2] = 0;
N= strlen(T);
K=0;
S=0;

while(K<=N && S != -1)


{
if(T[K]=='a')
I=0;
if(T[K]=='b')
I=1;
if(T[K]=='x')
I= 2;
S=F(S,I);
K=K+1;
}
if(S== -1)
INDEX = K-strlen(P);
else
INDEX= -1;

printf("\n P = %s",P);
printf("\n\n T = %s",T);
if(INDEX != -1)
printf("\n\n Index of P in T is %d", INDEX);
else
printf("\n\n P does not exist in T");
getch();
}
char F (char SK, char TK)
{
return(state[SK] [TK]);
}

Output:

You might also like