通过单词列表将两个字符串移动以比较每个单词
Moving two strings through a list of words to compare each word
我正在尝试使用两个字符串比较单词列表。例如,如果有人输入单词 "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;
}
相关文章:
- 文本文件中的单词链表
- 将对象移动到std::shared_ptr
- 何时在引用或唯一指针上使用移动语义
- 在指针的帮助下,文本文件中单词的频率
- 如何从具有移动语义的类对象中生成共享指针
- 将shared_ptr移动到<StructA>shared_ptr<变体<结构A、结构 B>>
- C / C++ 移位/偏移/向左或向右移动位图?
- 如何根据单词在文本中出现的概率输出单词
- MSVC将仅移动结构参数解释为指针
- 自定义先决条件对移动分配运算符有效吗
- 返回值优化:显式移动还是隐式
- 从字符串变量中逐字符读取单词
- 使用std::mt19937从字符串中返回一个随机单词
- 通过单词列表将两个字符串移动以比较每个单词
- 如何在C++中将单词的第一个字母移动到末尾:第 10 章 #16
- 在单词中移动字母n次
- 字符串将第一个单词移动到字符串的末尾
- 如何通过将特定的字符组合移动到空数组来"delete"单词和元音?
- 移动应用中的单词预测
- 移动字符串中的单词,单词之间使用空格作为分隔符