Namespaces
Variants

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

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

返回子字符串 [ pos , pos + rlen ) 的视图,其中 rlen count size ( ) - pos 中的较小值。

目录

参数

pos - 首字符位置
count - 请求长度

返回值

子字符串 [ pos , pos + rlen ) 的视图。

异常

pos > size ( ) 则抛出 std::out_of_range 异常。

复杂度

常量。

示例

#include <cstddef>
#include <iostream>
#include <stdexcept>
#include <string_view>
int main()
{
    typedef std::size_t count_t, pos_t;
    constexpr std::string_view data{"ABCDEF"};
    std::cout << data.substr() << '\n'; // ABCDEF,即 data[0, 5] 即 [0, 6)
    std::cout << data.substr(pos_t(1)) << '\n'; // BCDEF,即 [1, 6)
    std::cout << data.substr(pos_t(2), count_t(3)) << '\n'; // CDE,即 [2, 2 + 3)
    std::cout << data.substr(pos_t(4), count_t(42)) << '\n'; // EF,即 [4, 6)
    try
    {
        [[maybe_unused]]
        auto sub = data.substr(pos_t(666), count_t(1)); // 抛出异常:pos > size()
    }
    catch (std::out_of_range const& ex)
    {
        std::cout << ex.what() << '\n';
    }
}

可能的输出:

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

参见

复制字符
(公开成员函数)
在视图中查找字符
(公开成员函数)
返回子串
( std::basic_string<CharT,Traits,Allocator> 的公开成员函数)