C ++程序使用字符串库执行字符串匹配

在这里,我们将了解如何使用字符串库函数来匹配C ++中的字符串。在这里,我们使用该find()操作将子字符串的出现情况添加到主字符串中。此find()方法返回找到字符串的第一个位置。在这里,我们find()多次使用此函数来获取所有匹配项。

如果找到该项目,则此函数返回位置。但是,如果找不到,它将返回string::npos。

Input: The main string “aabbabababbbaabb” and substring “abb”
Output: The locations where the substrings are found. [1, 8, 13]

算法

String_Find(main_str,sub_str)

输入-要检查的主字符串和子字符串

输出-主字符串中子字符串的位置

pos := 0
while index = first occurrence of sub_str into the str in range pos to end of the string, do
   print the index as there is a match
   pos := index + 1
done

范例程式码

#include<iostream>
using namespace std;
main() {
   string str1 = "aabbabababbbaabb";
   string str2 = "abb";
   int pos = 0;
   int index;
   while((index = str1.find(str2, pos)) != string::npos) {
      cout << "Match found at position: " << index << endl;
      pos = index + 1; //new position is from next element of index
   }
}

输出:

Match found at position: 1
Match found at position: 8
Match found at position: 13