首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

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...

二次

代码语言:javascript
复制
#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";
    }
}

二次

产出:

二次

代码语言:javascript
复制
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)

代码语言:txt
复制
 © cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券