函數原型
string substr (size_t pos = 0, size_t len = npos) const;
功能描述:
-
從字符串中獲取想要的子串
參數:
pos:
-
- 要作為子字符串復制的第一個字符的位置。
- 如果等於字符串長度,則該函數返回一個空字符串。
- 如果該長度大於字符串長度,則拋出out_of_range。
- 注意:第一個字符由0值表示(不是1)。
len:
-
- 子字符串中要包含的字符數(如果字符串較短,則使用盡可能多的字符)。
- string :: npos的值表示直到字符串末尾的所有字符。
返回值:
- 帶有此對象子字符串的字符串對象。
樣例:
// string::substr #include <iostream> #include <string> int main () { std::string str="We think in generalities, but we live in details."; std::string str2 = str.substr (3,5); // "think" std::size_t pos = str.find("live"); // position of "live" in str std::string str3 = str.substr (pos); // get from "live" to the end std::cout << str2 << ' ' << str3 << '\n'; return 0; }