C++ Program to Implement the 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. }

advertisement
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
If you wish to look at all C++ Programming examples, go to C++ Programs.

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!
advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn