std::basic_string_view<CharT,Traits>::substr

From cppreference.com
 
 
 
 
constexpr basic_string_view
    substr(size_type pos = 0, size_type count = npos ) const;
(since C++17)

Returns a view of the substring [pos, pos + rcount), where rcount 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 + rcount).

Exceptions

std::out_of_range if pos > size()

Complexity

Constant.

Example

#include <cstddef>
#include <iostream>
#include <stdexcept>
#include <string_view>
 
int main()
{
    using namespace std::literals;
    std::size_t count{}, pos{};
    constexpr auto data{"ABCDEF"sv};
 
    std::cout << data.substr() << '\n'; // ABCDEF
    std::cout << data.substr(pos = 1) << '\n'; // BCDEF
    std::cout << data.substr(pos = 2, count = 3) << '\n'; // CDE
 
    std::cout << data.substr(pos = 4, count = 42) << '\n'; // EF
        // count -> 2 == size() - pos == 6 - 4
 
    try {
        data.substr(pos = 666, count = 1); // throws: pos > size()
    }
    catch(std::out_of_range const& ex) {
        std::cout << ex.what() << '\n';
    }
}

Output:

ABCDEF
BCDEF
CDE
EF
basic_string_view::substr: __pos (which is 666) > __size (which is 6)

See also

copies characters
(public member function)
find characters in the view
(public member function)