跳到主要内容

std::string_view substr() 方法

// Const version only
constexpr basic_string substr( size_type pos = 0, size_type count = npos ) const;

返回子字符串 [ pos, pos + rcount ) 的视图,其中 rcountstd::min(count, size() - pos)

参数

  • pos - 第一个字符的位置
  • count - 请求的长度

返回值

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

复杂度

常数 - O(1)

异常

如果 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
std::cout << data.substr(pos_t(1)) << '\n'; // BCDEF
std::cout << data.substr(pos_t(2), count_t(3)) << '\n'; // CDE

std::cout << data.substr(pos_t(4), count_t(42)) << '\n'; // EF
// count -> 2 == size() - pos == 6 - 4

try {
data.substr(pos_t(666), count_t(1)); // throws: 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)
本文源自此 CppReference 页面。它可能为了改进或编辑者的偏好而有所更改。点击“编辑此页面”查看本文档的所有更改。
悬停查看原始许可证。

std::string_view substr() 方法

// Const version only
constexpr basic_string substr( size_type pos = 0, size_type count = npos ) const;

返回子字符串 [ pos, pos + rcount ) 的视图,其中 rcountstd::min(count, size() - pos)

参数

  • pos - 第一个字符的位置
  • count - 请求的长度

返回值

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

复杂度

常数 - O(1)

异常

如果 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
std::cout << data.substr(pos_t(1)) << '\n'; // BCDEF
std::cout << data.substr(pos_t(2), count_t(3)) << '\n'; // CDE

std::cout << data.substr(pos_t(4), count_t(42)) << '\n'; // EF
// count -> 2 == size() - pos == 6 - 4

try {
data.substr(pos_t(666), count_t(1)); // throws: 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)
本文源自此 CppReference 页面。它可能为了改进或编辑者的偏好而有所更改。点击“编辑此页面”查看本文档的所有更改。
悬停查看原始许可证。