std::string 子串
时间: 2023-09-12 13:11:30 浏览: 58
您好!对于获取std::string的子串,可以使用substr()函数。这个函数可以接受两个参数,第一个参数是子串的起始位置,第二个参数是子串的长度。示例如下:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, world!";
std::string sub = str.substr(7, 5); // 从位置7开始,长度为5的子串
std::cout << sub << std::endl; // 输出 "world"
return 0;
}
```
在上面的例子中,我们从字符串"Hello, world!"中获取了从位置7开始,长度为5的子串"world"。希望能帮到您!如果还有其他问题,请随时提问。
相关问题
std::string 查找子串
std::string是C++标准库中的一个类,用于处理字符串。它提供了一系列的成员函数,其中包括查找子串的功能。
要查找子串,可以使用std::string的成员函数find()或rfind()。find()函数从字符串的开头开始查找子串,而rfind()函数从字符串的末尾开始查找子串。这两个函数都返回子串在字符串中的位置,如果找不到则返回std::string::npos。
下面是一个示例代码,演示如何使用find()函数查找子串:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, world!";
std::string subStr = "world";
size_t pos = str.find(subStr);
if (pos != std::string::npos) {
std::cout << "子串在位置:" << pos << std::endl;
} else {
std::cout << "未找到子串 << std::endl;
}
return 0;
}
```
输出结果为```
子串在位置:7
```
std::string截取子串
你可以使用`std::string`的`substr`函数来截取子串。`substr`函数接受两个参数,第一个参数是截取的起始位置,第二个参数是截取的长度。下面是一个示例代码:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
// 截取从索引位置2开始的5个字符
std::string subStr = str.substr(2, 5);
std::cout << subStr << std::endl; // 输出 "llo, "
return 0;
}
```
在上面的例子中,`str.substr(2, 5)`将返回从索引位置2开始的5个字符的子串"llo, "。