使用字符串库执行字符串匹配的 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 程序设计
C++
C#
MongoDB
MySQL
Javascript
PHP