string::find와 string::npos
string::find
- string::find()는 원하는 문자열의 위치를 찾을 때 사용한다.
- 사용 방법
size_t (문자열).find((찾을 문자열), (시작점)
string::npos
- string::npos는 문자열에서 특정 문자 또는 문자열을 찾지 못한 경우 반환되는 상수로 static const size_t npos = -1이다.
- 보통 size_t 자료형이 unsigned이기 때문에 -1값을 그대로 가지지 못하고 underflow로 인해 MAX값을 가지게 된다.
string::find와 string::npos 사용 예시
#include <iostream>
#include <string>
using namespace std;
int main() {
string alphabet = "abcdefgh";
string str;
cout << "The word you ares looking for: ";
cin >> str;
cout << endl;
int pos = 0;
if (alphabet.find(str) != std::string::npos) {
cout << "Found" << endl;
}
else {
std::cout << "Not found" << endl;
}
return 0;
}