命名空间
变体
操作

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

来自 cppreference.cn
< cpp‎ | string‎ | basic_string
 
 
 
std::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 起)

返回子字符串 [pospos + count)。如果请求的子字符串超出字符串的末尾,即 count 大于 size() - pos (例如,如果 count == npos),则返回的子字符串是 [possize())

1) 等价于 return basic_string(*this, pos, count);
2) 等价于 return basic_string(std::move(*this), pos, count);

目录

[编辑] 参数

pos - 要包含的第一个字符的位置
count - 子字符串的长度

[编辑] 返回值

包含子字符串 [pospos + count)[possize()) 的字符串。

[编辑] 异常

如果 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++ 标准。

缺陷报告 应用于 发布时的行为 正确的行为
LWG 847 C++98 没有异常安全保证 添加了强异常安全保证

[编辑] 另请参阅

复制字符
(public 成员函数) [编辑]
返回字符数
(public 成员函数) [编辑]
查找给定子字符串的第一次出现
(public 成员函数) [编辑]
constexpr size_type npos [static] 特殊值 size_type(-1),其确切含义取决于上下文[编辑]
返回子字符串
(std::basic_string_view<CharT,Traits> 的 public 成员函数) [编辑]