string类的substr
时间: 2024-03-10 11:41:46 浏览: 30
string类的substr()函数是用于提取字符串的子串。它接受两个参数,第一个参数是子串的起始位置,第二个参数是子串的长度(可选)。如果不指定第二个参数,则默认提取从起始位置到字符串末尾的所有字符。
下面是substr()函数的使用示例:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
// 提取从索引位置6开始的子串
std::string sub1 = str.substr(6);
std::cout << sub1 << std::endl; // 输出: World!
// 提取从索引位置0开始,长度为5的子串
std::string sub2 = str.substr(0, 5);
std::cout << sub2 << std::endl; // 输出: Hello
return 0;
}
```
相关问题
string的substr
string的substr函数用于获取字符串的子串。它接受两个参数:起始位置和子串的长度。起始位置可以是字符串中的任意位置,长度可以是任意非负整数。
示例用法:
```
string str = "Hello, world!";
string sub = str.substr(7, 5);
```
在上面的例子中,起始位置是7,长度是5,所以`sub`的值将是"world"。
如果省略第二个参数,则子串将包含起始位置到字符串末尾的所有字符:
```
string sub = str.substr(7);
```
在这种情况下,`sub`的值将是"world!"。
需要注意的是,起始位置是从0开始计数的,所以第一个字符的位置是0,第二个字符的位置是1,依此类推。如果指定的起始位置超出了字符串的范围,或者指定的长度超过了字符串剩余部分的长度,那么结果将是未定义的。
另外,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() 会一直提取到字符串末尾。
相关推荐
![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)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)