substr()
是C++语言函数,主要功能是复制子字符串,要求从指定位置开始,并具有指定的长度。
你可以给他指定长度,也可以不指定。
a.substr(x,y)它的默认长度是:x为0,y就为数组长度(a.size()),如果这样写a.substr(),那么会输出整个数组。
附上测试代码:
#include<iostream>
using namespace std;
int main()
{
string a = "helloworld!";
//测试1,输出为:hello
string b1=a.substr(0, 5);
cout << b1<<endl;
//测试二,输出:helloworld!
string b2 = a.substr();
cout << b2 << endl;
//测试3,输出为:helloworld!
string b3 = a.substr(0, 20);
cout << b3 << endl;
//出错,因为不符合默认值
//string b4 = a.substr(-1, 5);
//cout << b4 << endl;
}
运行结果: