C Program to Implement String Search Algorithm for Short Text Sizes

This is a C Program to perform string matching without using any specific library functions. 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 Implement the String Search Algorithm for Short Text Sizes. 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<string.h>
  3.  
  4. int main() {
  5.     char org[100], dup[100];
  6.     int i, j, k = 0, len_org, len_dup;
  7.     printf("NOTE:Strings are accepted only till blank space.");
  8.     printf("\nEnter Original String:");
  9.     fflush(stdin);
  10.     scanf("%s", &org);
  11.     fflush(stdin);
  12.     printf("Enter Pattern to Search:");
  13.     scanf("%s", &dup);
  14.  
  15.     len_org = strlen(org);
  16.     len_dup = strlen(dup);
  17.     for (i = 0; i <= (len_org - len_dup); i++) {
  18.         for (j = 0; j < len_dup; j++) {
  19.             //cout<<"comparing '"<<org[i + j]<<"' and '"<<dup[j]<<"'.";
  20.             if (org[i + j] != dup[j])
  21.                 break;
  22.         }
  23.         if (j == len_dup) {
  24.             k++;
  25.             printf("\nPattern Found at Position: %d", i);
  26.         }
  27.     }
  28.     if (k == 0)
  29.         printf("\nError:No Match Found!");
  30.     else
  31.         printf("\nTotal Instances Found = %d", k);
  32.     return 0;
  33. }

Output:

$ gcc StringSearch.c
$ ./a.out 
 
NOTE:Strings are accepted only till blank space.
Enter Original String: Stringsareacceptedonlytillblankspace.
Enter Pattern to Search: till
Pattern Found at Position: 22
Total Instances Found = 1

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.