【问题标题】:Moving two strings through a list of words to compare each word在单词列表中移动两个字符串以比较每个单词
【发布时间】:2018-04-02 18:52:07
【问题描述】:

我正在尝试使用两个字符串来比较单词列表。例如,如果有人输入单词"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",因为它是唯一的唯一单词。

【问题讨论】:

  • 您可以存储唯一词的列表,对吗?如果是这种情况,您想要的是 std::set
  • 这是一个编码网站的帮助。请向我们展示您需要帮助的代码。
  • 找到The most elegant way to iterate the words of a string 后,只需循环查看索引 (i) 和 (i+1) 处的单词并将它们放入 std::set。
  • 尝试使用 C++ 方式,使用std::stringstd::vector 和其他...当它起作用时,将其简化以适合您的老师。这样,你就不太可能养成坏习惯。为什么我以前从未想过这个建议?
  • 比较单词邻居的原因是什么?您将比较的结果用于什么?您的示例单词列表的预期输出是什么?你还有哪些案例?另外,请出示您的代码。

标签: c++ string unique


【解决方案1】:

你可以有一个函数,每次连续调用都会从输入中生成下一个单词。 在一个循环中,有两个调用将最后一个单词与下一个单词进行比较,直到到达输入的末尾。

#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;
}

【讨论】:

    猜你喜欢
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    相关资源
    最近更新 更多