Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

동일한 텍스트를 반복적으로 검색하는 C++ 프로그램(예:데이터 구조를 구축하여 성경)

<시간/>

동일한 텍스트를 반복적으로 검색하는 C++ 프로그램입니다.

알고리즘

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

예시

#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;
}

출력

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