C++ Program to Implement String Search Algorithm for Short Text Sizes

This C++ program performs naive 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.

This C++ program is successfully compiled and tested on our system. The program output is given below.

  1. /*
  2.  * C++ Program to Implement the String Search Algorithm for 
  3.  * Short Text Sizes
  4.  */
  5.  
  6. //enter string without spaces
  7. #include<iostream>
  8. using namespace std;
  9.  
  10. int main()
  11. {
  12.     char org[100], dup[100];
  13.     int i, j, k = 0, len_org, len_dup;
  14.     cout<<"NOTE:Strings are accepted only till blank space.";
  15.     cout<<"\nEnter Original String:";
  16.     fflush(stdin);
  17.     cin>>org;
  18.     fflush(stdin);
  19.     cout<<"Enter Pattern to Search:";
  20.     cin>>dup;
  21.  
  22.     len_org = strlen(org);
  23.     len_dup = strlen(dup);
  24.     for (i = 0; i <= (len_org - len_dup); i++)
  25.     {
  26.         for (j = 0; j < len_dup; j++)
  27.         {
  28.             //cout<<"comparing '"<<org[i + j]<<"' and '"<<dup[j]<<"'.";
  29.             if (org[i + j] != dup[j])
  30.                 break ;
  31.         }
  32.         if (j == len_dup)
  33.         {
  34.             k++;
  35.             cout<<"\nPattern Found at Position: "<<i;
  36.         }
  37.     }
  38.     if (k == 0)
  39.         cout<<"\nError:No Match Found!";
  40.     else
  41.         cout<<"\nTotal Instances Found = "<<k;
  42.     return 0;
  43. }

Output
 
NOTE:Strings are accepted only till blank space.
Enter Original String:allmenwenttoapall mall
Enter Pattern to Search:all
 
Pattern Found at Position: 0
Pattern Found at Position: 14
Total Instances Found = 2

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

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.