C Program to Perform Naive String Matching

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.

  1. #include<stdio.h>
  2. #include<conio.h>
  3. #include<string.h>
  4. int match(char st[100], char pat[100]);
  5. int main(int argc, char **argv) {
  6.     char st[100], pat[100];
  7.     int status;
  8.     printf("*** Naive String Matching Algorithm ***\n");
  9.     printf("Enter the String.\n");
  10.     gets(st);
  11.     printf("Enter the pattern to match.\n");
  12.     gets(pat);
  13.     status = match(st, pat);
  14.     if (status == -1)
  15.         printf("\nNo match found");
  16.     else
  17.         printf("Match has been found on %d position.", status);
  18.     return 0;
  19. }
  20. int match(char st[100], char pat[100]) {
  21.     int n, m, i, j, count = 0, temp = 0;
  22.     n = strlen(st);
  23.     m = strlen(pat);
  24.     for (i = 0; i <= n - m; i++) {
  25.         temp++;
  26.         for (j = 0; j < m; j++) {
  27.             if (st[i + j] == pat[j])
  28.                 count++;
  29.         }
  30.         if (count == m)
  31.             return temp;
  32.         count = 0;
  33.     }
  34.     return -1;
  35. }

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.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.