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

Here’s the list of Best Books in C Programming, Data Structures and Algorithms.

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification 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
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.