문자열 내에서 특정한 부분 문자열을 찾고 싶을 때 사용
•
pos를 지정하면, pos 혹은 그 이후의 인덱스에 대해서만 검색을 진행한다
•
당연히 문자 하나만 일치하면 안되고, 인자로 전달한 문자열과 완전히 일치해야 한다
문자열에 다른 문자열이 포함되어 있는 지 확인
#include <iostream>
#include <string>
int main()
{
std::string haystack = "It is like looking for a needle in a haystack";
std::string needle = "needle";
bool found = haystack.find(needle) != std::string::npos;
if (found) {
std::cout << "String found" << std::endl;
}
else {
std::cout << "String not found" << std::endl;
}
return 0;
}
C++
복사
vector에 주어진 요소가 포함되어 있는지 확인
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> v = { 4, 7, 5, 2, 6, 9 };
int key = 6;
if (std::find(v.begin(), v.end(), key) != v.end()) {
std::cout << "Element found";
}
else {
std::cout << "Element not found";
}
return 0;
}
C++
복사
// string
size_t find(const string& str, size_t pos = 0) const noexcept;
// c-string
size_t find(const char* s, size_t pos = 0) const;
// buffer
size_t find(const char* s, size_t pos, size_type n) const;
// character
size_t find(char c, size_t pos = 0) const noexcept;
C++
복사
매개변수
str
•
검색하려는 부분 문자열
pos
•
검색을 시작할 위치 (이 값이 문자열 길이보다 크다면, 일치하는 문자열을 찾을 수 없다. 기본은 인덱스 0부터 검색)
s
•
문자 배열을 가리키는 포인터
n
•
일치하는 문자 시퀀스의 길이
리턴값
•
검색하려는 문자열의 첫번째 문자의 위치를 리턴, 문자열을 발견하지 못하면, std::string::npos를 리턴한다.
static const size_t npos = -1;
C++
복사
백준 1436번 문제
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char* argv[]) {
ios_base::sync_with_stdio(0);
cin.tie(0);
// 몇 번째 종말의 수를 구할지 입력 받기
int N;
cin >> N;
int num = 665;
int count = 0;
// N번째 종말의 수를 구할때까지 반복
while (count != N) {
num++; // 666부터 검색 시작
// 666이 포함된 종말의 수를 발견하면
if (to_string(num).find("666") != string::npos) {
count++; // count == N이 되면 루프 탈출해서 결과 출력
}
// 종말의 수가 아닐 경우, num++ 하면서 검색 반복하기
}
// N번째 종말의 수 출력
cout << num;
return 0;
}
C++
복사