Namespaces
Variants

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

来自 zh.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() ) 的字符串。

异常

若 pos > size ( ) 则抛出 std::out_of_range 异常。

若因任何原因抛出异常,这些函数将不产生任何效果( 强异常安全保证 )。

复杂度

在 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> 的公开成员函数)