std::basic_string<CharT,Traits,Allocator>::subview
From cppreference.com
constexpr std::basic_string_view<CharT, Traits> subview( size_type pos = 0,
size_type count = npos ) const;
|
(since C++26) | |
Returns a view of the substring [pos, pos + rlen), where rlen is the smaller of count and size() - pos.
Equivalent to return std::basic_string_view<CharT, Traits>(*this).subview(pos, count);.
Parameters
| pos | - | position of the first character to include |
| count | - | length of the sub-view |
Return value
View of the substring [pos, pos + rlen).
Exceptions
std::out_of_range if pos > size().
Complexity
Constant.
Notes
| Feature-test macro | Value | Std | Feature |
|---|---|---|---|
__cpp_lib_string_subview |
202506L |
(C++26) | std::basic_string::subview, std::basic_string_view::subview
|
Example
Run this code
#include <cassert>
#include <iostream>
#include <string>
#include <string_view>
int main()
{
const std::string s{"Life is life!"};
assert(s.subview(5) == "is life!");
assert(s.subview(5, 13) == "is life!");
assert(s.subview(5, 2) == "is");
try
{
// pos is out of bounds, throws
const auto pos{s.length() + 13};
[[maybe_unused]] auto x_x{s.subview(pos)};
}
catch (const std::out_of_range& ex)
{
std::cout << "Exception: " << ex.what() << '\n';
}
}
Possible output:
Exception: basic_string_view::substr: __pos (which is 26) > __size (which is 13)
See also
| returns a substring (public member function) | |
(C++26) |
returns a sub-view (public member function of std::basic_string_view<CharT,Traits>)
|