string::find와 string::npos

KimY·2025년 3월 2일

string::find와 string::npos

string::find

  • string::find()는 원하는 문자열의 위치를 찾을 때 사용한다.
  • 사용 방법
size_t (문자열).find((찾을 문자열), (시작점)
// 시작점부터 탐색을 시작하여 '문자열'에서 '찾을 문자열'의 위치를 찾는다.
// find()가 찾는 문자열이 존재하지 않으면 string::npos를 리턴한다.

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;
}                      
profile
공부합니다

0개의 댓글