std::vector<std::string> 截取字符串到结尾
时间: 2024-04-08 17:27:49 浏览: 130
std::vector<std::string> 是C++标准库中的容器,用于存储一组字符串。你可以使用它来动态地管理字符串的集合,并且可以方便地进行插入、删除和访问操作。
要截取字符串到结尾,你可以使用std::string的substr函数来实现。substr函数接受两个参数,第一个参数是起始位置的索引,第二个参数是要截取的子字符串的长度。如果只指定起始位置而不指定长度,则截取从起始位置到字符串结尾的所有字符。
下面是一个示例代码,演示了如何将一个字符串截取为多个子字符串,并将它们存储在std::vector<std::string>中:
```cpp
#include <iostream>
#include <vector>
#include <string>
int main() {
std::string str = "Hello, world! This is a test string.";
std::vector<std::string> substrings;
// 截取字符串到结尾
while (!str.empty()) {
substrings.push_back(str);
str = str.substr(1); // 从索引1开始截取到结尾
}
// 输出截取后的子字符串
for (const auto& substring : substrings) {
std::cout << substring << std::endl;
}
return 0;
}
```
运行上述代码,你将得到以下输出:
```
Hello, world! This is a test string.
ello, world! This is a test string.
llo, world! This is a test string.
lo, world! This is a test string.
o, world! This is a test string.
, world! This is a test string.
world! This is a test string.
world! This is a test string.
orld! This is a test string.
rld! This is a test string.
ld! This is a test string.
d! This is a test string.
! This is a test string.
This is a test string.
This is a test string.
his is a test string.
is is a test string.
s is a test string.
is a test string.
is a test string.
s a test string.
a test string.
a test string.
test string.
test string.
est string.
st string.
t string.
string.
string.
tring.
ring.
ing.
ng.
g.
.
```
阅读全文