item.substr
时间: 2023-07-19 20:34:33 浏览: 38
在 C++ 中,`string` 类型提供了 `substr` 函数来获取字符串的子串。其语法如下:
```c++
string substr(size_t pos = 0, size_t len = npos) const;
```
其中,`pos` 表示子串的起始位置,`len` 表示子串的长度,默认为 `string::npos`,表示截取到字符串末尾。
例如,以下是使用 `substr` 函数获取子串的示例代码:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "hello, world!";
string sub = str.substr(7, 5);
cout << sub << endl;
return 0;
}
```
在以上示例中,`substr` 函数会从字符串 `str` 的第 7 个位置开始,获取长度为 5 的子串,即获取字符串 `"world"`。
需要注意的是,`substr` 函数返回的是 `string` 类型的子串,如果要将其转换为 `char*` 类型的字符串,可以使用 `c_str` 函数将其转换为 C 风格的字符串。例如:
```c++
string str = "hello, world!";
string sub = str.substr(7, 5);
const char* cstr = sub.c_str();
```
在以上示例中,`c_str` 函数将 `sub` 子串转换为 C 风格的字符串,并将其赋值给 `cstr` 指针。