std::basic_string<CharT,Traits,Allocator>::substr
来自cppreference.com
<tbody>
</tbody>
<tbody class="t-dcl-rev t-dcl-rev-num ">
</tbody><tbody>
</tbody>
| (1) | ||
basic_string substr( size_type pos = 0, size_type count = npos ) const; |
(C++23 前) (C++20 起为 constexpr) |
|
constexpr basic_string substr( size_type pos = 0, size_type count = npos ) const&; |
(C++23 起) | |
constexpr basic_string substr( size_type pos = 0, size_type count = npos ) &&; |
(2) | (C++23 起) |
返回子串 [pos, pos + count)。如果请求的子串越过字符串的结尾,即 count 大于 size() - pos(例如 count == npos),那么返回的子串是 [pos, size())。
1) 等价于
return basic_string(*this, pos, count);。2) 等价于
return basic_string(std::move(*this), pos, count);。参数
| pos | - | 要包含的首个字符的位置 |
| count | - | 子串的长度 |
返回值
含子串 [pos, pos + count) 或 [pos, size()) 的字符串。
异常
在 pos > size() 时抛出 std::out_of_range。
如果因为任何原因抛出了异常,那么这些函数无效果(强异常安全保证)。
复杂度
与 count 成线性。
注解
返回的字符串的分配器会被默认构造:新分配器将不一定 是 get_allocator() 的副本。
示例
运行此代码
#include <iostream>
#include <string>
int main()
{
std::string a = "0123456789abcdefghij";
// count 是 npos,返回 [pos, size())
std::string sub1 = a.substr(10);
std::cout << sub1 << '\n';
// pos 和 pos + count 都在边界内,返回 [pos, pos + count)
std::string sub2 = a.substr(5, 3);
std::cout << sub2 << '\n';
// pos 在边界内,pos+count 不在,返回 [pos, size())
std::string sub4 = a.substr(a.size() - 3, 50);
// 这等效于
// std::string sub4 = a.substr(17, 3);
// 因为 a.size() == 20,pos == a.size() - 3 == 17 而 a.size() - pos == 3
std::cout << sub4 << '\n';
try
{
// pos 在边界外,抛出
std::string sub5 = a.substr(a.size()+3, 50);
std::cout << sub5 << '\n';
}
catch(const std::out_of_range& e)
{
std::cout << "pos 超出了字符串的大小\n";
}
}
可能的输出:
abcdefghij
567
hij
pos 超出了字符串的大小
缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
| 缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
|---|---|---|---|
| LWG 847 | C++98 | 没有异常安全保证 | 添加强异常安全保证 |
参阅
| 复制字符 (公开成员函数) | |
| 返回字符数 (公开成员函数) | |
| 寻找给定子串的首次出现 (公开成员函数) | |
constexpr size_type npos [静态]
|
特殊值 size_type(-1),它的确切含义依赖语境
|
| 返回子串 ( std::basic_string_view<CharT,Traits> 的公开成员函数)
|