c+++substr
时间: 2023-12-30 22:06:02 浏览: 40
在C++中,`substr()`函数用于从一个字符串中提取子字符串。该函数需要两个参数:子字符串的起始位置和子字符串的长度。如果只提供起始位置,则默认提取从该位置到字符串末尾的所有字符。
以下是`substr()`函数的两种不同的语法:
引用:
```c++
string substr(size_type _Off = 0, size_type _Count = npos) const;
```
引用:
```c++
basic_string substr(size_type index, size_type num = npos ) const;
```
其中,`string`和`basic_string`都是C++中表示字符串的类。`size_type`是一个无符号整数类型,用于表示字符串的长度和位置。`_Off`和`index`参数表示子字符串的起始位置,`_Count`和`num`参数表示子字符串的长度。`npos`是一个常量,表示字符串的末尾位置。
以下是两个使用`substr()`函数的例子:
1.从字符串中提取子字符串:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello, World!";
string substr1 = str.substr(7, 5); // 从位置7开始提取长度为5的子字符串
string substr2 = str.substr(0, 5); // 从位置0开始提取长度为5的子字符串
cout << substr1 << endl; // 输出:World
cout << substr2 << endl; // 输出:Hello
return 0;
}
```
2.从字符串中提取剩余的子字符串:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello, World!";
string substr = str.substr(7); // 从位置7开始提取剩余的子字符串
cout << substr << endl; // 输出:World!
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)