std::basic_string<CharT,Traits,Allocator>::substr
From 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++標準に遡って適用されました。
| DR | 適用対象 | 公開された動作 | 正しい動作 |
|---|---|---|---|
| LWG 847 | C++98 | 例外安全性保証がなかった | 強力な例外安全性保証を追加 |
[編集] 関連項目
| 文字をコピーする (public member function) | |
| 文字数を返す (public member function) | |
| 指定された部分文字列が最初に現れる位置を見つける (public member function) | |
constexpr size_type npos [static] |
特殊な値 size_type(-1)。その正確な意味はコンテキストによって異なります。 |
| 部分文字列を返す ( std::basic_string_view<CharT,Traits> の public メンバー関数) |