◐ Shell
clean mode source ↗

std::basic_string<CharT,Traits,Allocator>::subview - cppreference.com

来自cppreference.com

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

返回子字符串 [pospos + rlen) 的视图,其中 rlencountsize() - pos 之间的较小值。

等价于 return std::basic_string_view<CharT, Traits>(*this).subview(pos, count);

参数

pos - 第一个要包含字符的位置
count - 子视图的长度

返回值

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

异常

pos > size() 时抛出 std::out_of_range

复杂度

常量。

注解

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

示例

#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 << "异常: " << ex.what() << '\n';
    }
}

可能的输出:

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

参阅