std::string::rfind()는 문자열 내에서 뒤쪽부터(오른쪽에서 왼쪽으로) 특정 문자열이나 문자, 또는 부분 문자열을 찾는 함수다. 이 함수는 마지막으로 나타나는 위치를 찾을 때 유용하게 사용할 수 있다.
size_t rfind(const std::string& str, size_t pos = npos) const;
size_t rfind(const char* s, size_t pos = npos) const;
size_t rfind(char c, size_t pos = npos) const;
pos): 검색을 시작할 위치로 기본값은 npos(문자열의 끝)다.std::string::npos를 반환한다.#include <iostream>
#include <string>
int main() {
std::string text = "Hello, world! Hello, C++!";
// 마지막으로 나타나는 "Hello" 찾기
size_t pos = text.rfind("Hello");
if (pos != std::string::npos) {
std::cout << "'Hello' found at index: " << pos << std::endl;
} else {
std::cout << "'Hello' not found." << std::endl;
}
return 0;
}
'Hello' found at index: 14
"Hello"는 문자열 "Hello, world! Hello, C++!"에서 두 번 등장한다.rfind()는 뒤쪽에서 탐색하여 마지막 "Hello"가 시작하는 인덱스 14를 반환한다.#include <iostream>
#include <string>
int main() {
std::string text = "This is a simple example.";
// 마지막으로 나타나는 문자 'e' 찾기
size_t pos = text.rfind('e');
if (pos != std::string::npos) {
std::cout << "Last 'e' found at index: " << pos << std::endl;
} else {
std::cout << "'e' not found." << std::endl;
}
return 0;
}
Last 'e' found at index: 21
"This is a simple example."에서 문자 'e'는 여러 번 등장한다.rfind('e')는 마지막 'e'가 나타나는 인덱스 21을 반환한다.rfind()는 기본적으로 문자열의 끝에서부터 탐색을 시작하지만, 원하는 위치부터 역순으로 탐색을 시작하도록 위치를 지정할 수 있다.
#include <iostream>
#include <string>
int main() {
std::string text = "abc abc abc";
// 5번째 인덱스부터 역순으로 "abc" 찾기
size_t pos = text.rfind("abc", 5);
if (pos != std::string::npos) {
std::cout << "'abc' found at index: " << pos << std::endl;
} else {
std::cout << "'abc' not found." << std::endl;
}
return 0;
}
'abc' found at index: 4
rfind("abc", 5)는 인덱스 5부터 역순으로 탐색을 시작한다."abc"가 반환된다.반환값이 std::string::npos인지 확인
rfind()가 찾는 문자열을 발견하지 못하면 std::string::npos를 반환하므로, 이를 확인하는 것이 중요하다.검색 시작 위치가 문자열 범위를 벗어나면 동작하지 않음
pos 매개변수로 지정한 위치가 문자열 길이를 초과하면 rfind()는 npos를 반환한다.부분 문자열이 비어 있을 경우
"")이라면, rfind()는 pos 위치를 반환한다.