Namespaces
Variants

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

From cppreference.net
std::basic_string
(1)
basic_string substr ( size_type pos = 0 , size_type count = npos ) const ;
(C++23まで)
(constexprはC++20から)
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 ) 、その正確な意味は文脈に依存
部分文字列を返す
( std::basic_string_view<CharT,Traits> の公開メンバ関数)