C++ string substr()

共有成員函數
<string>

std::string::substr

string substr (size_t pos = 0, size_t len = npos) const;
產生子串
返回一個新建的初始化爲string對象的子串的拷貝string對象。

子串是,在字符位置pos開始,跨越len個字符(或直到字符串的結尾,以先到者爲準)對象的部分。

參數

pos
第一個字符的位置被複製爲子串。
如果這是等於字符串的長度,該函數返回一個空字符串。
如果這是大於字符串的長度,它會拋出out_of_range。
注意:第一個字符表示爲值0(不是1)。
len
字符數在子包括(如果字符串是短,儘可能多的字符可以在需要使用)。
字符串::非營利值表示的所有字符,直到字符串的結尾。

size_t is an unsigned integral type (the same as member type string::size_type).

返回值

string object with a substring of this object.

Example

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 (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;
}
 


Output:
think live in details.
發佈了72 篇原創文章 · 獲贊 29 · 訪問量 38萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章