C++ Program to Repeatedly Search the Same Text (such as Bible by building a Data Structure)


This is a C++ program to repeatedly search the same text.

Algorithms

Begin
   Take the original string and pattern to be searched as input.
   org_len = store the length of original string
   pat_len = store the length of pattern
   for i = 0 to (org_len - pat_len)
      for j = 0 to pat_len - 1
         if (org[i + j] != patt[j])
            if (j == pat_len)
               Increase m.
      Print the position at which the pattern is found
   if (m == 0)
      Print no match found
   else
      Print the total number of instances found.
   return 0
End

Example

#include<iostream>
#include<string.h>
using namespace std;
int main() {
   char org[150], patt[150];
   int i, j, m = 0, org_len, pat_len;
   cout << "\nEnter Original String:";
   cin >> org;
   cout << "Enter Pattern to Search:";
   cin >> patt;
   org_len = strlen(org); //store the length of original string
   pat_len = strlen(patt); //store the length of pattern
   for (i = 0; i <= (org_len - pat_len); i++) {
      for (j = 0; j < pat_len; j++) {
         if (org[i + j] != patt[j])
         break;
      }
      if (j == pat_len) {
         m++;
         cout << "\nPattern Found at Position: " << i;
      }
   } if (m == 0)
   cout << "\nNo Match Found.";
   else
      cout << "\nTotal Number of Instances Found = " << m;
   return 0;
}

Output

Enter Original String:thisistutorialspoint.thisisac++program
Enter Pattern to Search:is

Pattern Found at Position: 2
Pattern Found at Position: 4
Pattern Found at Position: 23
Pattern Found at Position: 25
Total Number of Instances Found = 4

Updated on: 30-Jul-2019

117 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements