This is a C Program to perform string matching using Naive String Matching. A text and a pattern is given as input. The pattern is searched for in the text and all instances of the pattern are given as output.
Here is source code of the C Program to Perform Naive String Matching. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
#include<stdio.h>
#include<conio.h>
#include<string.h>
int match(char st[100], char pat[100]);
int main(int argc, char **argv) {
char st[100], pat[100];
int status;
printf("*** Naive String Matching Algorithm ***\n");
printf("Enter the String.\n");
gets(st);
printf("Enter the pattern to match.\n");
gets(pat);
status = match(st, pat);
if (status == -1)
printf("\nNo match found");
else
printf("Match has been found on %d position.", status);
return 0;
}
int match(char st[100], char pat[100]) {
int n, m, i, j, count = 0, temp = 0;
n = strlen(st);
m = strlen(pat);
for (i = 0; i <= n - m; i++) {
temp++;
for (j = 0; j < m; j++) {
if (st[i + j] == pat[j])
count++;
}
if (count == m)
return temp;
count = 0;
}
return -1;
}
Output:
$ gcc NaiveMatch.c $ ./a.out *** Naive String Matching Algorithm *** Enter the String. [email protected] Enter the pattern to match. Dharm Match has been found on 6 position.
Sanfoundry Global Education & Learning Series – 1000 C Programs.
advertisement
advertisement
Here’s the list of Best Books in C Programming, Data Structures and Algorithms.
Related Posts:
- Practice BCA MCQs
- Watch Advanced C Programming Videos
- Apply for Computer Science Internship
- Apply for C Internship
- Check C Books