我正在编写一个程序来完成这个练习,该程序接收单词并打印单词列表而不重复。然而,当问题进一步被要求将一个选择的词(我不喜欢)替换为" Bleep"时,我感到困惑。
以下是代码:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<string>words;
string temp;
while (cin>>temp)
words.push_back(temp);
cout << "Number of words: " << words.size() << "\n";
for (int i = 0; i<words.size(); ++i)
if(i == 0 || words[i-1] != words[i])
cout << words[i] << '\n';
return 0;
}
如何添加代码来更改用户输入的字符串,例如&#39; cute&#39;到&#39; Bleep&#39;?非常感谢你。
答案 0 :(得分:3)
您可以将输入字与禁止字列表进行比较,并根据输入字是否在列表中继续。
#include <algorithm>
vector<string> badWords = { "bad", "words", "for", "example", "cute" };
while (cin>>temp)
{
if (std::find(badWords.begin(), badWords.end(), temp) == badWords.end())
words.push_back(temp);
else
words.push_back("bleep");
}
答案 1 :(得分:1)
只需更改
即可while (cin>>temp)
words.push_back(temp);
这个块到下面的块:
vector<string> bad_words = { "beautiful", "nice", "sweet", "cute" }; // The badwords you have
while (cin>>temp){
for(int i=0; i<bad_words.size(); i++){
if(bad_words[i]==temp){
temp="bleep";
break;
}
}
words.push_back(temp);
}
答案 2 :(得分:0)
我是对的吗
打印单词列表而不重复
你的意思是将你的初始字符串向量转换为唯一字符串的向量?在这种情况下,您的算法是错误的。看看部分
input: word1 word2 word3 word1 word1 word1
output: word1 word2 word3 word1
该算法不处理分开两次或多次重复的情况。例如
{{1}}
输出向量包括两个相等的单词。