C++学习笔记(四)~substr()函数

substr(pos,len)

作用
        返回一个新构造的串对象,其值初始化为该对象的子字符串的副本。子字符串是对象的一部分,从字符位置pos开始并跨越len个字符(或直到字符串的结尾,以先到者为准)。

海轰的理解
        对于字符串string,从位置pos开始,截取长度为len而产生的子字符串。

示例

测试代码

#include <iostream>
using namespace std;

int main()
{
    string a = "HelloWorld";
    // substr(pos,len)

    // 默认pos=0 len为原字符串长度 返回:HelloWorld
    cout << "默认构造参数:" << a.substr() << endl;

    // 从0开始 截取长度为3 的子字符串 返回:Hel
    cout << "从位置0开始 长度为3" << a.substr(0, 3) << endl;

    // len越界 返回从pos开始,直到原字符串最后的子字符串 返回:lloWorld
    cout << "len 越界:" << a.substr(2, 20) << endl;

    // pos越界 抛出异常:out_of_range 抛出异常
    cout << "pos 越界:" << a.substr(20, 2) << endl;
    return 0;
}

运行结果
在这里插入图片描述

参考资料

http://www.cplusplus.com/reference/string/string/substr/

猜你喜欢

转载自blog.csdn.net/weixin_44225182/article/details/107634416