HOWTO · C++
C++에서 문자열의 하위 문자열을 찾는 방법
이 기사에서는 C++에서 문자열에 하위 문자열이 포함되어 있는지 확인하는 여러 방법을 소개합니다.
이 기사는 C++의 문자열에서 주어진부분 문자열을 찾는 방법을 보여줍니다.
find 메서드를 사용하여 C++의 문자열에서 하위 문자열 찾기
문제를 해결하는 가장 간단한 방법은 내장 된string 메소드 인find 함수이며 다른string 객체를 인수로 사용합니다.
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl using std::string;
int main() {
string str1 = "this is random string oiwao2j3";
string str2 = "oiwao2j3";
string str3 = "random s tring";
str1.find(str2) != string::npos
? cout << "str1 contains str2" << endl
: cout << "str1 does not contain str3" << endl;
str1.find(str3) != string::npos
? cout << "str1 contains str3" << endl
: cout << "str1 does not contain str3" << endl;
return EXIT_SUCCESS;
}
출력:
str1 contains str2
str1 does not contain str3
또는find를 사용하여 두 문자열의 특정 문자 범위를 비교할 수 있습니다. 이렇게하려면 범위의 시작 위치와 길이를find 메소드에 인수로 전달해야합니다.
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl using std::string;
using std::stoi;
int main() {
string str1 = "this is random string oiwao2j3";
string str3 = "random s tring";
constexpr int length = 6;
constexpr int pos = 0;
str1.find(str3.c_str(), pos, length) != string::npos
? cout << length << " chars match from pos " << pos << endl
: cout << "no match!" << endl;
return EXIT_SUCCESS;
}
출력:
6 chars match from pos 0
rfind 메서드를 사용하여 C++의 문자열에서 하위 문자열 찾기
rfind 메소드는find와 유사한 구조를 가지고 있습니다. rfind를 사용하여 마지막 부분 문자열을 찾거나 주어진 부분 문자열과 일치하도록 특정 범위를 지정할 수 있습니다.
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl using std::string;
using std::stoi;
int main() {
string str1 = "this is random string oiwao2j3";
string str2 = "oiwao2j3";
str1.rfind(str2) != string::npos
? cout << "last occurrence of str3 starts at pos " << str1.rfind(str2)
<< endl
: cout << "no match!" << endl;
return EXIT_SUCCESS;
}
출력:
last occurrence of str3 starts at pos 22