c++的string如何取从下标A到下标B的字符串
时间: 2024-04-15 19:31:59 浏览: 18
在C++中,可以使用`substr`成员函数来从一个`std::string`对象中提取从下标A到下标B的子字符串。
`substr`函数的型如下:
```
std::string substr(size_t pos = 0, size_t count = std::string::npos) const;
```
其中,`pos`参数表示起始下标,`count`参数表示要提取的字符数。如果不指定`count`,则默认提取从起始下标到字符串末尾的所有字符。
以下是一个示例代码:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
std::string sub = str.substr(7, 5); // 从下标7开始提取5个字符
std::cout << "Substring: " << sub << std::endl;
return 0;
}
```
在这个示例中,我们定义了一个字符串`str`,然后使用`substr`函数从下标7开始提取5个字符,并将结果保存在`sub`中。最后,我们打印出提取的子字符串。
输出结果将是:
```
Substring: World
```
通过指定起始下标和要提取的字符数,我们可以从`std::string`中获取指定范围的子字符串。请注意,下标从0开始计数。如果起始下标超出字符串的长度,或者提取的字符数超过可用字符数量,`substr`函数将返回一个部分子字符串。