'C++' std::find, std::rfind (+ std::strchr)

토스트·2025년 4월 26일

'C++' std::string

목록 보기
8/12

1. 문자열 찾기 (+ C-style 문자열)

find

size_t find(const string& str, size_t pos = 0) const noexcept;
size_t find(const char* s, size_t pos = 0) const;

: 문자열의 pos 위치를 기준으로 오른쪽 방향으로 탐지합니다. 문자열 str(s)이 가장 처음 나타나는 위치를 반환합니다.

rfind

size_t rfind(const string& str, size_t pos = npos) const noexcept;
size_t rfind(const char* s, size_t pos = npos) const;

: 문자열의 pos 위치를 기준으로 왼쪽 방향으로 탐지합니다. 문자열 str(s)이 가장 처음 나타나는 위치를 반환합니다.

<예시 코드>

#include <iostream>
#include <string>

using namespace std;

int main() {
	string str = "banana";

	cout << "find: " << str.find("na") << endl;
	cout << "rfind: " << str.rfind("na");

	return 0;
}

결과

2. C-style 부분 문자열을 이용하여 찾기

find

size_t find(const char* s, size_t pos, size_type n) const;

: 문자열의 pos 위치를 기준으로 오른쪽 방향으로 탐지합니다. C-style 문자열인 s의 처음부터 n개까지의 문자를 기준으로 가장 처음 나타나는 위치를 반환합니다.

rfind

size_t rfind(const char* s, size_t pos, size_t n) const;

: 문자열의 pos 위치를 기준으로 왼쪽 방향으로 탐지합니다. C-style 문자열인 s의 처음부터 n개까지의 문자를 기준으로 가장 처음 나타나는 위치를 반환합니다.

<예시 코드>

#include <iostream>
#include <string>

using namespace std;

int main() {
	string str = "banana";

	cout << "find: " << str.find("naba", 1, 2) << endl; // na가 기준
	cout << "rfind: " << str.rfind("anas", string::npos, 3); // ana가 기준

	return 0;
}

결과

3. 문자 찾기

find

size_t find(char c, size_t pos = 0) const noexcept;

: 문자열의 pos 위치를 기준으로 오른쪽 방향으로 탐지합니다. 문자 c가 가장 처음 나타나는 위치를 반환합니다.

rfind

size_t rfind(char c, size_t pos = npos) const noexcept;

: 문자열의 pos 위치를 기준으로 왼쪽 방향으로 탐지합니다. 문자 c가 가장 처음 나타나는 위치를 반환합니다.

<예시 코드>

#include <iostream>
#include <string>

using namespace std;

int main() {
	string str = "banana";

	cout << "find: " << str.find('a', 2) << endl;
	cout << "rfind: " << str.rfind('n');

	return 0;
}

결과

strchr

const char* strchr(const char* str, int character);
char* strchr(char* str, int character);

: <cstring> 헤더에 있는 C-style 문자열에서 character 문자가 처음 나타나는 위치의 포인터를 반환합니다. 만약 character 문자를 찾지 못하면 NULL을 반환합니다.

C에서 자주 사용되었던 함수로 C++에서는 더 안정적이고, 가독성이 높은 find 함수를 사용하는 것을 권장합니다.

0개의 댓글