从一个字符串中获取 2-5 个连续的单词短语,我得到了 2 个工作,但在做 3 个时遇到麻烦

getting 2-5 consecutive word phrases from a string I got 2 to work but having trouble doing 3

本文关键字:工作 遇到 麻烦 短语 一个 字符串 获取 单词 连续      更新时间:2023-10-16
vector <string> oneWordPhrase;
vector <string> twoWordPhrase;
vector <string> threeWordPhrase;
vector<string>::iterator it1;
vector<string>::iterator it2;
string str="hello my is bob oh hey jay oh";
string split = str;
string word;
stringstream stream(split);
while( getline(stream, word, ' ') )
{
  oneWordPhrase.push_back(word);
}//used to split sentence into words
for(it1=oneWordPhrase.begin(); it1!=oneWordPhrase.end(); it1++)
{
    if(it1+1 == oneWordPhrase.end())
        break;
    twoWordPhrase.push_back(*it1 + ' ' + *(it1+1));
}//getting two word phrases
cout<<"two word---------------n";
for(int i=0; i<twoWordPhrase.size(); i++)
    cout<<twoWordPhrase[i]<<endl;
for(it1=twoWordPhrase.begin(); it1!=twoWordPhrase.end(); it1++)
{
    it2=oneWordPhrase.begin()+2;
    threeWordPhrase.push_back(*it1 + ' ' + *it2);
    ++it2;  /* was hoping that I can get each word after "is" but it 
             didn't allow me. the problem is here */
}//getting three word phrases
cout<<"three word---------------n";
for(int i=0; i<twoWordPhrase.size(); i++)
    cout<<threeWordPhrase[i]<<endl;

我让我的两个短语正确打印,即

你好我的

我的是

是鲍勃

鲍勃·

哦 嘿

嘿杰伊

周杰伦哦

但是,我的三个单词短语打印出来

你好我的是

我的是

鲍勃是

鲍勃哦是

哦,嘿是

嘿杰伊是

周杰伦是

对于三个单词短语,我希望将"hello my is"my is bob"is bob oh"bob oh hey"一直打印到"hey jay oh"。

我将我的it2指向myWordPhrase.begin()+2,并希望它会像在数组中一样增加1,但事实并非如此。

我评论了给我带来问题的代码部分

我很确定如果我能找出 3 个单词短语,我可以做 4 个和 5 个单词短语,所以对 3 个单词的任何帮助将不胜感激!

当你这样做*it2 = oneWordPhrase.begin() + 2 它总是给你一个单词短语向量中的第三个成员。您可以使用计数器而不是迭代器,因为您需要迭代两个向量:

vector <string> oneWordPhrase;
vector <string> twoWordPhrase;
vector <string> threeWordPhrase;
vector<string>::iterator it1;
vector<string>::iterator it2;
string str="hello my is bob oh hey jay oh";
string split = str;
string word;
stringstream stream(split);
while( getline(stream, word, ' ') )
{
  oneWordPhrase.push_back(word);
}//used to split sentence into words
for(it1=oneWordPhrase.begin(); it1!=oneWordPhrase.end(); it1++)
{
    if(it1+1 == oneWordPhrase.end())
        break;
    twoWordPhrase.push_back(*it1 + ' ' + *(it1+1));
}//getting two word phrases
cout<<"two word---------------n";
for(int i=0; i<twoWordPhrase.size(); i++)
    cout<<twoWordPhrase[i]<<endl;
for(int i=0; i!=twoWordPhrase.size() - 2; i++)
{
    threeWordPhrase.push_back( twoWordPhrase[i] + ' ' + oneWordPhrase[i + 2] );
      /* was hoping that I can get each word after "is" but it 
             didn't allow me. the problem is here */
}//getting three word phrases
cout<<"three word---------------n";
for(int i=0; i<twoWordPhrase.size() - 2; i++)
    cout<<threeWordPhrase[i]<<endl;