std::basic_string<CharT,Traits,Allocator>::substr
提供: cppreference.com
basic_string substr( size_type pos = 0, size_type count = npos ) const; |
||
部分文字列 [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
関連項目
文字をコピーします (パブリックメンバ関数) | |
文字数を返します (パブリックメンバ関数) | |
文字列内の文字を探します (パブリックメンバ関数) |