std::basic_string::substr
| basic_string substr( size_type pos = 0, size_type count = npos ) const; |  |  | 
|---|
返回一个子字符串。[pos, pos+count)如果请求的子字符串扩展到字符串的末尾,或者count == npos,返回的子字符串是[pos,size())...
参数
| pos | - | position of the first character to include | 
|---|---|---|
| count | - | length of the substring | 
返回值
包含子字符串的字符串。[pos, pos+count)...
例外
std::out_of_range如果pos >size()...
复杂性
线性在count...
例
二次
#include <string>
#include <iostream>
 
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);
    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& e) {
        std::cout << "pos exceeds string size\n";
    }
}二次
产出:
二次
abcdefghij
567
hij
pos exceeds string size二次
另见
| copy | copies characters (public member function) | 
|---|---|
| sizelength | returns the number of characters (public member function) | 
| find | find characters in the string (public member function) | 
 © cppreference.com在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。
本文档系腾讯云开发者社区成员共同维护,如有问题请联系 cloudcommunity@tencent.com

