std::basic_string<CharT,Traits,Allocator>::substr
来自cppreference.com
                    
                                        
                    < cpp | string | basic string
                    
                                                            
                    |   basic_string substr( size_type pos = 0, size_type count = npos ) const;  | 
(C++20 前) | |
|   constexpr basic_string substr( size_type pos = 0, size_type count = npos ) const;  | 
(C++20 起) | |
返回子串 [pos, pos+count) 。若请求的子串越过 string 的结尾,或若 count == npos ,则返回的子串为 [pos, size()) 。
参数
| pos | - | 要包含的首个字符的位置 | 
| count | - | 子串的长度 | 
返回值
含子串 [pos, pos+count) 的 string 。
异常
若 pos > size() 则为 std::out_of_range
复杂度
与 count 成线性
注解
如同以 basic_string(data()+pos, count) 构造返回的 string ,这隐含将会默认构造返回的 string 的分配器——新分配器将不是 this->get_allocator() 的副本。
示例
运行此代码
#include <string> #include <iostream> 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::cout << sub4 << '\n'; try { // pos 在边界外,抛出 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
参阅
|   复制字符  (公开成员函数)  | |
|   返回字符数  (公开成员函数)  | |
|   于字符串中寻找字符  (公开成员函数)  | |
|    [静态]  | 
  特殊值。准确含义依赖语境  (公开静态成员常量)  |