Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++에서 문자열에 하위 문자열이 포함되어 있는지 확인

<시간/>

여기서는 문자열 라이브러리 함수를 사용하여 C++에서 문자열을 일치시키는 방법을 볼 수 있습니다. 여기서 find() 작업을 사용하여 하위 문자열의 발생을 기본 문자열로 가져옵니다. 이 find() 메서드는 문자열이 발견된 첫 번째 위치를 반환합니다. 여기에서 이 find() 함수를 여러 번 사용하여 모든 일치 항목을 가져옵니다.

항목이 발견되면 이 함수는 위치를 반환합니다. 그러나 찾지 못하면 string::npos를 반환합니다.

따라서 하위 문자열이 기본 문자열에 있는지 확인하려면 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
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