Namespaces
Variants

std::basic_string<CharT,Traits,Allocator>::substr

ja.cppreference.net より
 
 
 
std::basic_string
 
basic_string substr( size_type pos = 0, size_type count = npos ) const;
(1) (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() ) の範囲。

例外

std::out_of_range posが pos > size ( ) の場合。

何らかの理由で例外がスローされた場合、これらの関数は何も効果を持ちません( strong exception safety guarantee )。

計算量

count に対して線形。

注記

返される文字列のアロケータはデフォルト構築されます:新しいアロケータは 必ずしも get_allocator() のコピーであるとは限りません。

例

#include <iostream>
#include <string>
int main()
{
    std::string a = "0123456789abcdefghij";
    // countがnposの場合、[pos, size())を返す
    std::string sub1 = a.substr(10);
    std::cout << sub1 << '\n';
    // posとpos + countの両方が範囲内の場合、[pos, pos + count)を返す
    std::string sub2 = a.substr(5, 3);
    std::cout << sub2 << '\n';
    // posが範囲内でpos + countが範囲外の場合、[pos, size())を返す
    std::string sub4 = a.substr(a.size() - 3, 50);
    // これは事実上以下と同等
    // std::string sub4 = a.substr(17, 3);
    // a.size() == 20, pos == a.size() - 3 == 17, a.size() - pos == 3 のため
    std::cout << sub4 << '\n';
    try
    {
        // posが範囲外の場合、例外をスロー
        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 例外安全性保証がなかった 強い例外安全性保証を追加

関連項目

constexpr size_type npos [static] 特殊な値 size_type(-1)。その正確な意味は文脈に依存します。
(C++26)
部分ビューを返す
(パブリックメンバ関数)
文字をコピーする
(パブリックメンバ関数)
文字数を返す
(パブリックメンバ関数)
指定された部分文字列が最初に現れる位置を検索する
(パブリックメンバ関数)
部分文字列を返す
(std::basic_string_view<CharT,Traits>のパブリックメンバ関数)