이것은 또 다른 문자열 일치 방법입니다. 이 접근 방식에서는 벡터를 사용하여 부분 문자열을 검색합니다.
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(기본, 하위 문자열)
입력 − 본문과 부분 문자열.
출력 - 패턴이 발견된 위치
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