C++中substr函数的用法

#include<iostream>
#include<string>
using namespace std;

int main(){
    string str("12345abc");
    string a = str.substr(0, 5);
    cout << a << endl;

    system("pause");
    return 0;
}

输出结果为:12345

 

1. 用途:一种构造string的方法。

2. 形式:str.substr(pos, n)。

3. 解释:返回一个string,包含str中从pos开始的n个字符的拷贝(pos的默认值是0,n的默认值是s.size() - pos,即不加参数会默认拷贝整个str)。

4. 补充:若pos的值超过了string的大小,则substr函数会抛出一个out_of_range异常;若pos+n的值超过了string的大小,则substr会调整n的值,只拷贝到string的末尾。

 

转自  https://www.cnblogs.com/xzxl/p/7243490.html

posted @ 2018-11-07 20:57  Z--Y  阅读(1933)  评论(0编辑  收藏  举报