Namespaces
Variants

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

来自 zh.cppreference.net
 
 
 
 
constexpr std::basic_string_view<CharT, Traits> subview( size_type pos = 0,
                                                         size_type count = npos ) const;
(C++26 起)

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

参数

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

返回值

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

异常

若 则抛出 std::out_of_rangepos > size()。

复杂度

常数。

注解

功能特性测试宏 值 标准 功能
__cpp_lib_string_subview 202506L (C++26) std::basic_string_view::subview, std::basic_string::subview

示例

#include <cassert>
#include <iostream>
#include <string_view>

int main()
{
    const std::string_view 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';
    }
}

可能的输出:

Exception: basic_string_view::substr: __pos (which is 26) > __size (which is 13)

参阅

返回子串
(公开成员函数)
(C++26)
返回子视图
(公开成员函数)