string substr (size_t pos = 0, size_t len = npos) const;
substr()
主要功能是復制(截取更準確)子字符串,要求從指定位置 pos
開始,并具有指定的長度 len
。如果沒有指定長度或者超出了源字符串的長度,則子字符串將延續到源字符串的結尾 npos
。
參數:
- pos 為所需的子字符串的起始位置。默認值為0,即字符串中第一個下標位置。
- len 為指定向后截取的字符個數,默認設定為字符串結尾 npos 。
返回值:
- 返回截取的 string 。若兩個參數都不設置,則返回整個源string,這其實就是對源string進行拷貝。
示例:
#include <iostream>
#include <string>
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 strstring str3 = str.substr(pos); // get from "live" to the endstring str4 = str.substr(); //拷貝stringcout << str2 << endl;cout << str3 << endl;cout << str4 << endl;return 0;
}
結果:
think
live in details.
We think in generalities, but we live in details.