通过单词列表将两个字符串移动以比较每个单词

Moving two strings through a list of words to compare each word

本文关键字:单词 移动 字符串 比较 两个 列表      更新时间:2023-10-16

我正在尝试使用两个字符串比较单词列表。例如,如果有人输入单词 "Hello Man Tomato Yum Zebra",我想将我的两个向量设置为前两个单词,然后将两个向量移动。S1将是hello,然后S2为Man。比较它们并移动向量后,S1现在为Man,S2为Tomato。继续这样做,直到我到达最后两个单词,当我这样做时,打印出我们看到的所有独特单词。

唯一的事情是我无法将整个单词列表存储在字符串中,而不是使用集合,向量或地图。

让我知道您是否需要更多详细信息或某些代码。

#include <iostream>
#include <string>
using namespace::std;
int main(){
string S;
string V;
string Unique;
string Dup;
cin >> S;
cin >> V;
int temp;
//For unique strings
if (S.length() != V.length()){
    Unique += S;
    Unique += ' ';
    Unique += V;
}
else if (S[0] != V[0]){
        Unique += S;
        Unique += ' ';
        Unique += V;
}
//for dup strings
else if (S[0] == V[0]){
    for (int i=1; i < S.length(); ++i){
        if (S[i] != V[i]) {
        //if there is a letter that does match they are not duplicates so     add them to unique
         Unique += S;
         Unique += ' ';
         Unique += V;
         break;
            }
        temp = i;
    // this will break when it finds it's a dup or when i reaches the length of S and they are duplicates
    }    
        if (temp ==  S.length()-1){
    cout << "Duplicate string" << endl;
           }
    }
//cout the unique words
for (int i=0; i < Unique.length(); i++){
cout << Unique[i];
    }
 cout << endl;
    return 0;
}

因此,从本质上讲,我正在插入两个字符串并进行比较,以查看它们是唯一的还是重复的。我希望能够通过输入两个单词移动向量,我将如何使向量在整个输入中移动而不保存整个输入?

3个单词的输入的预期输出"Hello Hello Man"只是"Man",因为它是唯一的唯一单词。

您可以拥有一个函数,每个连续呼叫都会从输入中生成下一个单词。在循环中,有两个将最后一个单词与下一个单词进行比较直到输入结束的呼叫。

#include <iostream>
#include <string>
using namespace std;
//global variables; when updated
//return the next word from nextWord function
int start, space;
string nextWord(string wordList)
{
    //find the next space
    space = wordList.find(" ", space+1);
    //find the next word
    string word = wordList.substr(start, space-start);
    //restrict the search range
    start = space + 1;
    return word;
}
int main()
{
    //set initial values
    string words;
    getline(cin, words);
    string last = nextWord(words);
    string next;
    while (true)
    {
        if (space == -1)
            break;
        next = nextWord(words);
        if (last == next){
            cout << next << endl;
        }
        last = next;
    }
    return 0;
}