string str("hello"); string str2 = str.substr(3,2)
时间: 2024-03-18 08:45:58 浏览: 23
这段代码的作用是从字符串 `str` 的第 4 个字符开始(因为下标从 0 开始,所以第 4 个字符的下标是 3),截取 2 个字符,将它们赋值给字符串 `str2`。
具体来说,`str.substr(3,2)` 的返回值是一个新的字符串对象,它的内容是从 `str` 的第 4 个字符开始的 2 个字符,即 `"lo"`。然后这个新的字符串对象被赋值给 `str2`,因此 `str2` 的值为 `"lo"`。
需要注意的是,`substr()` 函数的第一个参数是截取的起始位置,第二个参数是截取的长度。如果第二个参数被省略,则默认截取从起始位置到字符串末尾的所有字符。如果起始位置超出字符串的长度,或者长度参数为负数,那么 `substr()` 函数会返回一个空字符串。
相关问题
string.substr
string.substr() 是 C++ STL 中的一个函数,用于从字符串中提取子串。
函数格式如下:
```
string substr (size_t pos, size_t len) const;
```
其中,pos 表示子串起始位置,len 表示子串长度。
示例代码:
```c++
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
std::string sub_str = str.substr(7, 5); // 从第 7 个位置开始,提取长度为 5 的子串
std::cout << sub_str << std::endl; // 输出 World
return 0;
}
```
注意,pos 的取值范围是 [0, size()-1],即字符串的有效下标范围。如果 pos 超出了该范围,会抛出 std::out_of_range 异常。而如果 len 超出了字符串剩余长度,substr() 会一直提取到字符串末尾。
str.substr(7)
`str.substr(7)`表示从字符串`str`的第7个字符(从0开始计数)开始,截取从该位置到字符串结尾的所有字符,得到一个新的`std::string`对象作为结果。
例如,对于字符串`str = "Hello, World!"`,`str.substr(7)`的结果为`"World!"`,因为从第7个字符(即字符'W')开始到字符串结尾的所有字符构成了一个字符子串"World!"。
需要注意的是,`substr`函数返回的是一个新的`std::string`对象,因此对其进行任何字符串操作都不会影响原始字符串`str`。如果需要修改原始字符串`str`,可以使用`replace`函数等其他字符串操作函数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)