将字符串拆分为单词向量
Split a string into a vector of words
我有一个类似string
的"ABC DEF "
,末尾有空白。我想把它转换成像{"ABC" "DEF"}
这样的字符串的vector
,所以我使用了stringstream
:
string s = "ABC DEF ";
stringstream ss(s);
string tmpstr;
vector<string> vpos;
while (ss.good())
{
ss >> tmpstr;
vpos.push_back(tmpstr);
}
然而,结果vpos
是{"ABC" "DEF" "DEF"}
。为什么最后一个单词会在向量中重复?如果需要使用stringstream
,正确的代码是什么?
ss.good()
只会告诉到目前为止情况是否良好。它不会告诉你你读的下一篇文章会很好。
使用
while (ss >> tmpstr) vpos.push_back(tmpstr);
现在您先阅读tmpstr
,然后检查流的状态。它相当于:
for (;;) {
istream &result = ss >> tmpstr;
if (!result) break;
vpos.push_back(tmpstr);
}
相关文章:
- 包含换行符分隔的单词的文件和C++中这些单词的字符串向量的大小是否相同?
- 创建单词对齐的字符向量
- 如何用单词排列向量中的每个字符升序?
- 如何使用向量 c++ 迭代文件中单词的位置
- 将字符串拆分为单个单词并将它们放置在向量中
- 如何从C 向量访问单个单词
- 菜鸟问题:试图审查向量中的特定单词
- 我可以在不循环访问数组/向量的情况下检查数组/向量中的单词吗?
- 如何在带有给定特定前缀的向量中打印出单词
- C - 将文本文件读为一串单词,然后将字符串分为向量
- 分类包含数字和单词的字符串向量
- 在 C++11 中计算字母和单词的双字母组合的 std::线程向量的问题
- 在向量中通过一个单词查找行
- 使用单词键将多个行号的向量添加到我的地图中
- 计算字符向量中单词的出现次数
- 在向量中搜索C++字符串s中的单词
- 向量中的常用单词用C++表示单词出现的次数
- 计算向量中偶数长度的单词
- 单词比较 - 向量/getopt
- 将字符串拆分为单词向量