std::basic_string<CharT,Traits,Allocator>::substr
提供: cppreference.com
< cpp | string | basic string
basic_string substr( size_type pos = 0, size_type count = npos ) const; |
(C++20未満) | |
constexpr basic_string substr( size_type pos = 0, size_type count = npos ) const; |
(C++20以上) | |
部分文字列 [pos, pos+count)
を返します。 要求された部分文字列が文字列の終端を超える場合、返される文字列は [pos,
size()
)
になります。
目次 |
[編集] 引数
pos | - | 含める最初の文字の位置 |
count | - | 部分文字列の長さ |
[編集] 戻り値
部分文字列 [pos, pos+count)
を持つ文字列。
[編集] 例外
pos >
size()
の場合 std::out_of_range。
[編集] 計算量
count
に比例。
[編集] ノート
返される文字列は basic_string(data()+pos, count) によって行われたかのように構築されます。 これは、返される文字列のアロケータはデフォルト構築されるということを暗に示しています。 新しいアロケータは this->
get_allocator()
のコピーではありません。
[編集] 例
Run this code
#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); 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
[編集] 関連項目
文字をコピーします (パブリックメンバ関数) | |
文字数を返します (パブリックメンバ関数) | |
文字列内の文字を探します (パブリックメンバ関数) | |
[静的] |
特殊な値です。正確な意味は文脈に依存します (パブリック静的メンバ定数) |