std::basic_string<CharT,Traits,Allocator>::substr
来自 cppreference.cn
< cpp | string | basic string
(1) | ||
basic_string substr( size_type pos = 0, size_type count = npos ) const; |
(until C++23) (constexpr since C++20) |
|
constexpr basic_string substr( size_type pos = 0, size_type count = npos ) const&; |
(since C++23) | |
constexpr basic_string substr( size_type pos = 0, size_type count = npos ) &&; |
(2) | (since 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);。
目录 |
[edit] 参数
pos | - | 要包含的第一个字符的位置 |
count | - | 子字符串的长度 |
[edit] 返回值
包含子字符串 [
pos,
pos + count)
或 [
pos,
size()
)
的字符串。
[edit] 异常
std::out_of_range 如果 pos > size()。
如果由于任何原因抛出异常,这些函数不起作用(强异常安全保证)。
[edit] 复杂度
与 count 成线性关系。
[edit] 注意
返回字符串的分配器是默认构造的:新的分配器可能不是 get_allocator()
的副本。
[edit] 示例
运行此代码
#include <iostream> #include <string> int main() { std::string a = "0123456789abcdefghij"; // count is npos, returns [pos, size()) std::string sub1 = a.substr(10); std::cout << sub1 << '\n'; // both pos and pos + count are within bounds, returns [pos, pos + count) std::string sub2 = a.substr(5, 3); std::cout << sub2 << '\n'; // pos is within bounds, pos + count is not, returns [pos, size()) std::string sub4 = a.substr(a.size() - 3, 50); // this is effectively equivalent to // std::string sub4 = a.substr(17, 3); // since a.size() == 20, pos == a.size() - 3 == 17, and a.size() - pos == 3 std::cout << sub4 << '\n'; try { // pos is out of bounds, throws std::string sub5 = a.substr(a.size() + 3, 50); std::cout << sub5 << '\n'; } catch (const std::out_of_range& ex) { std::cout << ex.what() << '\n'; } }
可能的输出
abcdefghij 567 hij basic_string::substr: __pos (which is 23) > this->size() (which is 20)
[edit] 缺陷报告
以下行为变更的缺陷报告被追溯应用于先前发布的 C++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
LWG 847 | C++98 | 没有异常安全保证 | 添加了强异常安全保证 |
[edit] 参见
复制字符 (public member function) | |
返回字符数 (public member function) | |
查找给定子字符串的首次出现 (public member function) | |
constexpr size_type npos [static] |
特殊值 size_type(-1),其确切含义取决于上下文 |
返回子字符串 (public member function of std::basic_string_view<CharT,Traits> ) |