basic_string substr(size_type _Off = 0, size_type _Count = npos) const;
在使用时,可以设置npos(拷贝长度),也可以不设置。
#include<string>
#include<iostream>
using namespace std;
int main()
{
string s = "12345abcdefff";
string res1 = s.substr(1, 5);
cout << res1 << endl; //res1 = "12345"
string res2 = s.substr(5, 5); //第一个参数为pos的位置,也就是下标
cout << res2 << endl; //res2 = "abcde"
string res3 = s.substr(5); //不写最后一个参数,默认到字符串结尾
cout << res3 << endl; //res3 = "abcdefff"
string res4 = s.substr(5, 10); //第二个参数越界,但是可以正常取到字符串结尾停止
cout << res4 << endl; //res4 = "abcdefff"
//注:如果第一个参数大于字符串长度是会报错的
}
返回值一个string,包含s中从pos开始的n个字符的拷贝。pos的默认值是0,n的默认值是s.size() - pos,即不加参数会默认拷贝整个s。
注:
若pos的值超过了string的大小,则substr函数会抛出一个out_of_range异常
若pos+n的值超过了string的大小,则substr会调整n的值,只拷贝到string的末尾