【发布时间】:2020-07-27 22:04:24
【问题描述】:
我想实现一个函数,它将string 作为输入行(通过getline())并在向量中分隔(拆分)单词。我试过这个:
vector<string> split(const string &s)
{
vector<string> ret;
int j = 0, i = 0; // j=="start word boundary", i=="end word boundary"
while (i != s.size())
{
//get words
while (i != s.size() && !isspace(s[i]))
{
i++;
}
//at least one word found (so the 'i' index is not at the beginning of string)
if (!i)
{
ret.push_back(s.substr(j, i - j));
}
//now look for blanks
j = i;
//ignore blanks
while (j != s.size() && isspace(s[j]))
{
j++;
}
//get position for next words back
i = j;
}
return ret;
}
然后尝试查看结果:
int main()
{
string tmp;
while (getline(cin, tmp))
{
vector<string> vec = split(tmp);
for (string s : vec)
{
cout << s << endl;
}
}
}
但是什么都看不到。为什么?
【问题讨论】:
-
A
std::istringstream对这项任务非常有用。只是说。关于你的代码,split2!=split,所以从那开始。 -
我建议阅读函数
std::string::first_of和std::string::first_not_of". For example, you can define whitespace characters in a string and find positions that are not whitespace usingstd::string::first_not_of"。 -
@ThomasMatthews 谢谢,我会查的。这只是通过索引和
substr实现它的一种执行方式,没有迭代器。