std::basic_string<CharT,Traits,Allocator>::substr
basic_string substr( size_type pos = 0, size_type count = npos ) const;
|
(1) | (C++23까지) (C++20부터 constexpr) |
constexpr basic_string
substr( size_type pos = 0, size_type count = npos ) const&;
|
(C++23부터) | |
constexpr basic_string substr( size_type pos = 0, size_type count = npos ) &&;
|
(2) | (C++23부터) |
부분 문자열을 반환합니다 [pos, pos + count). 요청된 부분 문자열이 문자열 끝을 넘어 확장되는 경우, 즉 count이 size() - pos보다 큰 경우 (예: count == npos인 경우), 반환되는 부분 문자열은 [pos, size())입니다.
return basic_string(*this, pos, count);와 동일합니다.return basic_string(std::move(*this), pos, count);와 동일합니다.매개변수
| pos | - | 포함할 첫 번째 문자의 위치 |
| count | - | 부분 문자열의 길이 |
반환값
부분 문자열을 포함하는 문자열
[
pos
,
pos
+
count
)
또는
[
pos
,
size()
)
.
예외
std::out_of_range 만약 pos > size ( ) 인 경우.
어떤 이유로든 예외가 발생하면, 이 함수들은 아무런 효과를 가지지 않습니다( strong exception safety guarantee ).
복잡도
count 에 대해 선형적입니다.
참고 사항
반환된 문자열의 할당자는 기본 생성됩니다: 새로운 할당자는
get_allocator()
의 복사본이
아닐 수 있습니다
.
예제
#include <iostream> #include <string> int main() { std::string a = "0123456789abcdefghij"; // count가 npos인 경우, [pos, size()) 반환 std::string sub1 = a.substr(10); std::cout << sub1 << '\n'; // pos와 pos + count가 모두 범위 내에 있는 경우, [pos, pos + count) 반환 std::string sub2 = a.substr(5, 3); std::cout << sub2 << '\n'; // pos는 범위 내에 있지만 pos + count는 범위를 벗어나는 경우, [pos, size()) 반환 std::string sub4 = a.substr(a.size() - 3, 50); // 이는 다음과 동일하게 작동합니다 // std::string sub4 = a.substr(17, 3); // a.size() == 20, pos == a.size() - 3 == 17, 그리고 a.size() - pos == 3 이므로 std::cout << sub4 << '\n'; try { // pos가 범위를 벗어나면 예외 발생 std::string sub5 = a.substr(a.size() + 3, 50); std::cout << sub5 << '\n'; } catch (const std::out_of_range& ex) { std::cout << ex.what() << '\n'; } }
가능한 출력:
abcdefghij 567 hij basic_string::substr: __pos (which is 23) > this->size() (which is 20)
결함 보고서
다음의 동작 변경 결함 보고서들은 이전에 발표된 C++ 표준에 소급 적용되었습니다.
| DR | 적용 대상 | 게시된 동작 | 올바른 동작 |
|---|---|---|---|
| LWG 847 | C++98 | 예외 안전성 보장이 없었음 | 강력한 예외 안전성 보장이 추가됨 |
함께 보기
constexpr size_type npos [static]
|
특수 값 size_type(-1)으로, 정확한 의미는 문맥에 따라 달라집니다
|
(C++26) |
하위 뷰를 반환합니다 (공개 멤버 함수) |
| 문자를 복사합니다 (공개 멤버 함수) | |
| 문자 개수를 반환합니다 (공개 멤버 함수) | |
| 주어진 부분 문자열이 처음 나타나는 위치를 찾습니다 (공개 멤버 함수) | |
| 부분 문자열을 반환합니다 ( std::basic_string_view<CharT,Traits>의 공개 멤버 함수)
|