【发布时间】:2020-01-26 01:46:53
【问题描述】:
我正在尝试编写代码,通过在每个空格字符处拆分字符串来将字符串初始化为向量。不知何故,临时向量不会占据位置,也不会正确拆分字符串。
#include <iostream>
#include <string>
#include <vector>
std::vector<std::string> splitStr(std::string s, char cut = 32) {
std::string temp = s;
int begin = 0;
std::vector<std::string> v;
for (int i = 0; i < temp.length() - 1; ++i) {
if ((int) cut == (int) temp[i]) {
v.push_back(temp.substr(begin, i));
begin = i + 1;
}
}
return v;
}
using namespace std;
int main() {
for (string e : splitStr("Hello this is a test!", ' ')) {
cout << e << endl;
}
}
我认为附加到向量时会出错,但我不明白为什么会这样。 谁能告诉我我做错了什么?
【问题讨论】:
-
查看this了解如何用空格分割字符串
-
感谢您的帮助,但我仍然希望我的代码能够正常工作。
-
std::string::substr的第二个参数是长度。这意味着您需要将v.push_back(temp.substr(begin, i));更改为v.push_back(temp.substr(begin, i - begin));,然后您当然需要处理最后一句话。 -
我完全错了,非常感谢!
-
我马上看到 2 个问题:如果有相邻空格,您的代码会将空字符串推送到向量中 + 最后一个单词永远不会添加到向量中
标签: c++ string vector split push-back