std::basic_string<CharT,Traits,Allocator>::substr
來自 cppreference.com
< cpp | string | basic_string
(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 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)
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 847 | C++98 | 沒有異常安全保證 | 添加了強異常安全保證 |
[編輯] 另請參閱
複製字元 (public 成員函式) | |
返回字元數 (public 成員函式) | |
查詢給定子字串的第一次出現 (public 成員函式) | |
constexpr size_type npos [static] |
特殊值 size_type(-1),其確切含義取決於上下文 |
返回子字串 ( std::basic_string_view<CharT,Traits> 的 public 成員函式) |