# std::string::substr
```cpp
string substr (size_t pos = 0, size_t len = npos) const;
```
## 產生子字串 Generate substring
回傳一個新建構的字符串物件,並將其值初始化為該物件的子字符串。
Returns a newly constructed string object with its value initialized to a copy of a substring of this object.
子字符串是該物件的一部分,從字符位置pos開始並跨越len個字符(或直到字串的結尾,以先到者為準)。
The substring is the portion of the object that starts at character position pos and spans len characters (or until the end of the string, whichever comes first
## 參數 Parameters
### pos
1.欲複製之子字符串的第一個字符的位置。
2.如果它等於字符串長度,則該函數返回一個空字符串。
3.如果該長度大於字符串長度,則拋出**out_of_range**(超出範圍)。
4.注意:第一個字符的位置是0(不是1)。
1.Position of the first character to be copied as a substring.
2.If this is equal to the string length, the function returns an empty string.
3.If this is greater than the string length, it throws **out_of_range**.
4.Note: The first character is denoted by a value of 0 (not 1).
### len
1. 子字符串中包含的字符數(如果字符串較短,則使用盡可能多的字符)。
2. **string :: npos**的值表示直到字符串末尾的所有字符。
1. Number of characters to include in the substring (if the string is shorter, as many characters as possible are used).
2. A value of **string::npos** indicates all characters until the end of the string.
## 回傳值 Return Value
以字符串之子字符串建構的字符串物件。
A string object with a substring of this object.
## 範例 Example
```cpp
// 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;
}
```
| string | We think in |
| ---- | ---- |
| index | 0123456789 |
Output:
think live in details.
{"metaMigratedAt":"2023-06-16T00:33:25.916Z","metaMigratedFrom":"Content","title":"std::string::substr","breaks":true,"contributors":"[{\"id\":\"525bf276-3a10-40a6-9f6b-88b006427d96\",\"add\":1950,\"del\":106}]"}