Namespaces
Variants

std::basic_string_view<CharT,Traits>::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.

Parameters

pos - position of the first character
count - requested length

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_view::subview, std::basic_string::subview

Example

#include <iostream>
#include <string_view>
using namespace std::literals::string_view_literals;

static_assert("Life is life!"sv.subview(5) == "is life!");
static_assert("Life is life!"sv.subview(5, 2) == "is");
static_assert("Life is life!"sv.subview(5, 13) == "is life!");

int main()
{
    try
    {
        const auto sv{"Life is life!"sv};
        const auto pos{sv.length() + 13}; // “pos” is out of bounds of “sv”
        const auto x_x{sv.subview(pos)};  // throws
    }
    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) [edit]
(C++26)
returns a sub-view
(public member function of std::basic_string<CharT,Traits,Allocator>) [edit]