使用字串庫執行字串匹配的 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