C++ Program to Repeatedly Search the Same Text
Posted by Superadmin on August 10 2022 04:17:25

C++ Program to Repeatedly Search the Same Text

 

 

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.

 

Here is source code of the C++ Program to Repeatedly Search the Same Text (such as Bible by building a Data Structure). The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

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

Output:

$ g++ RepeatedSearch.cpp
$ a.out
 
NOTE:Strings are accepted only till blank space.
Enter Original String:ThisC++programperformsnaivestringmatchingwithoutusinganyspecificlibraryfunctions.Atextandapatternisgivenasinput.Thepatternissearchedforinthetextandallinstancesofthepatternaregivenasoutput.h
Enter Pattern to Search:in
 
Pattern Found at Position: 30
Pattern Found at Position: 38
Pattern Found at Position: 50
Pattern Found at Position: 100
Total Instances Found = 4
------------------
(program exited with code: 0)
Press return to continue