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
热门推荐
10 朋友新年祝福语大全 简短
11 新年祝福语简短大方兔年
12 搬新家礼物祝福语简短
13 同学见面花束祝福语简短
14 五一假期祝福语幽默简短
15 离职欢送敬酒祝福语简短
16 对学弟的祝福语简短
17 考老师辞职祝福语简短
18 祝福语驱散霉运的话简短