std::string substr() 方法
- 自 C++20 起
- 直到 C++20
// Const version only
constexpr basic_string substr( size_type pos = 0, size_type count = npos ) const;
// Const version only
basic_string substr( size_type pos = 0, size_type count = npos ) const;
返回子字符串 [ pos, pos + count )。
如果请求的子字符串超出字符串的末尾,即 count
大于 size() - pos
(例如,如果 count == npos
),则返回的子字符串是 [ pos, size() )。
参数
pos
- 要包含的第一个字符的位置count
- 子字符串的长度
返回值
包含子字符串 [ pos, pos + count ) 或 [ pos, size() ) 的字符串。
复杂度
线性于 count
- O(count)。
异常
如果 pos > size()
,则抛出 std::out_of_range
。
备注
返回的字符串的构造方式如同 basic_string(data() + pos, count)
,这意味着返回的字符串的分配器将被默认构造——新的分配器可能不是get_allocator()
的副本。
示例
#include <string>
#include <iostream>
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& e) {
std::cout << "pos exceeds string size\n";
}
}
输出
abcdefghij
567
hij
pos exceeds string size