使用向量实现字符串匹配的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