public member function
<string>

std::basic_string::substr

basic_string substr (size_type pos = 0, size_type len = npos) const;
生成子字串
返回一個新構造的 basic_string 物件,其值初始化為此物件的子字串的副本。

子字串是物件中從字元位置 pos 開始並跨越 len 個字元的部分(或者直到字串的末尾,以先到者為準)。

引數

pos
要複製為子字串的第一個字元的位置。
如果這等於字串長度,則該函式返回一個空字串。
如果這大於字串長度,則會丟擲 out_of_range 異常。
注意:第一個字元用值表示0(不是1).
len
要包含在子字串中的字元數(如果字串較短,則使用盡可能多的字元)。
basic_string::npos值表示直到字串末尾的所有字元。

成員型別size_type是一種無符號整型型別。

返回值

一個 basic_string 物件,包含此物件的子字串。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// string::substr
#include <iostream>
#include <string>

int main ()
{
  std::string str="We think in generalities, but we live in details.";
                                              // (quoting Alfred N. Whitehead)

  std::string str2 = str.substr (12,12);         // "generalities"

  std::string::size_type 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;
}

輸出
generalities live in details.


複雜度

未指定,但通常與返回物件的 長度 成線性關係。

迭代器有效性

沒有變化。

資料競爭

該物件被訪問。

異常安全

強保證: 如果丟擲異常,則 basic_string 中沒有任何更改。

如果 pos 大於 字串長度,則會丟擲 out_of_range 異常。
如果該型別使用預設分配器,如果函式需要分配儲存空間但失敗,則會丟擲bad_alloc異常。

另見