[C++]string::substr
string substr (size_t pos = 0, size_t len = npos) const;
substr()
主要功能是复制(截取更准确)子字符串,要求从指定位置 pos
开始,并具有指定的长度 len
。如果没有指定长度或者超出了源字符串的长度,则子字符串将延续到源字符串的结尾 npos
。
参数:
- pos 为所需的子字符串的起始位置。默认值为0,即字符串中第一个下标位置。
- len 为指定向后截取的字符个数,默认设定为字符串结尾 npos 。
返回值:
- 返回截取的 string 。若两个参数都不设置,则返回整个源string,这其实就是对源string进行拷贝。
示例:
#include #include using namespace std;int main(){ string str = \"We think in generalities, but we live in details.\"; string str2 = str.substr(3, 5); // \"think\" size_t pos = str.find(\"live\"); // position of \"live\" in str string str3 = str.substr(pos); // get from \"live\" to the end string str4 = str.substr(); //拷贝string cout << str2 << endl; cout << str3 << endl; cout << str4 << endl; return 0;}
结果:
think
live in details.
We think in generalities, but we live in details.