将字符串拆分为单词向量

Split a string into a vector of words

本文关键字:单词 向量 拆分 字符串      更新时间:2023-10-16

我有一个类似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);
}