使用向量實現字串匹配的 C++ 程式


這是一種字串匹配方法。我們在這個方法中用向量來搜尋一個子字串。

在 C++ 中,我們可以輕鬆利用標準庫建立向量。我們將主字串和將被搜尋的字串作為向量,再在主字串中搜索。當找到一個匹配項時,該函式會返回地址,並將其從主字串中移除。所以在下一次迭代中,它從位置 0 開始重新搜尋。

對於多次出現的情況,我們使用迴圈多次搜尋匹配項,並返回位置。

Input: Main String: “ABAAABCDBBABCDDEBCABC”, Pattern “ABC”
Output: Pattern found at position: 4
Pattern found at position: 10
Pattern found at position: 18

演算法

vector_pattern_search(main, substr)

輸入− 主文字和子字串。

輸出 − 找到該模式的位置

Begin
   p := starting point of the main string
   while r is not at the end of substr and p is not at the end of main, do
      r := starting of substr
      while item at position p & r are not same, and p in main, do
         p := p + 1
         i := i + 1
      done
      q := p
      while item at pos p & r are same, and r in substr and p in main, do
         p := p + 1
         i := i + 1
         r := r + 1
      done
      if r exceeds the substr, then
         delete first occurrence of substr from main
         return the position where substr is found

      if p exceeds main string, then
         return 0
         q := q + 1
         p := q
   done
End

示例程式碼

#include <iostream>
#include <string>
#include <vector>
using namespace std;

void take_string(vector<char> &string){
   char c;
   while(true){
      c = getchar();
      if(c == '\n'){
         break;
      }
      string.push_back(c);
   }
}

void display(vector<char> string){
   for(int i = 0; i<string.size(); i++){
      cout << string[i];
   }
}

int match_string(vector<char>& main, vector<char> substr){
   vector<char>::iterator p,q, r;
   int i = 0;

   p = main.begin();

   while (r <= substr.end() && p <= main.end()){
      r = substr.begin();
      while (*p != *r && p < main.end()){
         p++;
         i++;
      }
      q = p;

      while (*p == *r && r <= substr.end() && p<=main.end()){
         p++;
         i++;
         r++;
      }

      if (r >= substr.end()){
         main.erase(main.begin(), q + 1);
         return (i - substr.size() + 1);
      }

      if (p >= main.end())
         return 0;
         p = ++q;
   }
}

輸出

Enter main String: C++ is programming language. It is object oriented language
Enter substring to find: language

Match found at Position = 20
Match found at Position = 52

更新於: 30-Jul-2019

517 次檢視

開啟你的職業

完成課程後獲得認證

立即開始
Advertisement
© . All rights reserved.