vector <string> oneWordPhrase;
vector <string> twoWordPhrase;
vector <string> threeWordPhrase;
string str="hello my is bob oh hey jay oh";
vector<string>::iterator it1;
vector<string>::iterator it2;
我把句子用str语言分成单个单词并将它们存储到名为oneWordPhrase的向量中。因此,矢量的大小为7
for(it1=oneWordPhrase.begin(); it1!=oneWordPhrase.end(); it1++)
{
if(it1+1 == oneWordPhrase.end())
break; /* if we reach the last element of the vector
get out of loop because we reached the end */
twoWordPhrase.push_back(*it1 + ' ' + *(it1+1));
}//gets each 2 consecutive words in the sentence
cout<<"two word---------------\n";
for(int i=0; i<twoWordPhrase.size(); i++)
cout<<twoWordPhrase[i]<<endl;
这会产生正确的输出:
你好我的
我的
是bob
鲍勃哦
哦,嘿嘿 嘿杰伊jay oh
for(int i=0; i<twoWordPhrase.size()-1; i++)
{
it1=twoWordPhrase.begin()+i;
it2=oneWordPhrase.begin()+i+2;
if(it1==twoWordPhrase.end()-1)
break; //signal break but doesnt work
threeWordPhrase.push_back(*it1 + ' ' + *it2);
}
cout<<"three words-----------\n";
for(int i=0; i<threeWordPhrase; i++)
cout<<threeWordPhrase[i]<<endl;
这会产生正确的输出,但最后有两行空格
你好我的
我的是鲍勃
是bob哦
鲍勃哦嘿
哦,嘿,杰伊//空白
//空白
我还尝试在for循环中使用迭代器来发出中断信号,但它没有用。为什么要打印两行额外的空格?
答案 0 :(得分:1)
要回答原始问题,发布的代码是正确的。正如JosephMansfield所怀疑的那样,显示代码(未发布)中出现了错误,如demonstrated here。
关于风格和最佳实践的评论,我认为以下是更惯用的C ++:
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <iterator>
using namespace std;
typedef vector<string> strings;
int main() {
string s = "one two three four five";
/* stringstream is a stream just like std::cout
but reads/writes from/to a string
instead of the standard input/output */
stringstream ss(s);
/* std::vector has a 2 argument constructor
which fills the vector with all elements between two iterators
istream_iterator iterates throuw the stream as if
using operator>> so it reads word by word */
strings words =
strings(istream_iterator<string>(ss), istream_iterator<string>());
strings threeWords;
for(size_t i = 0; i < words.size()-2; ++i)
threeWords.push_back(words[i] + ' ' + words[i+1] + ' ' + words[i+2]);
for(size_t i = 0; i < threeWords.size(); ++i)
cout << i << ": " << threeWords[i] << endl;
return 0;
}
单词拆分代码的灵感来自this post