std::basic_string<CharT,Traits,Allocator>::substr
cppreference.com
<tbody>
</tbody>
<tbody class="t-dcl-rev t-dcl-rev-num ">
</tbody><tbody>
</tbody>
| (1) | ||
basic_string substr( size_type pos = 0, size_type count = npos ) const; |
( C++20) | |
constexpr basic_string substr( size_type pos = 0, size_type count = npos ) const; |
( C++20) ( C++23) |
|
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()).
1)
return basic_string(*this, pos, count);.2)
return basic_string(std::move(*this), pos, count);.| pos | , | |
| count |
, [pos, pos + count) [pos, size()).
std::out_of_range, pos > size().
count.
#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++:
| LWG 847 | C++98 |
| (public -) | |
| (public -) | |
| (public -) | |
[static] |
. (public static -) |
(C++17) |
(public - std::basic_string_view<CharT,Traits>)
|