【发布时间】:2015-10-13 22:53:44
【问题描述】:
我正在创建一个接收句子或段落的程序。然后它会询问用户他们想做什么。 - 隐蔽到所有大写 - 隐藏到所有小写字母 - 删除空格 - 拆分单词并删除重复项 - 在字符串中搜索一个单词
我得到了所有这些,但我不知道如何拆分单词并删除重复项..
选择第四个选择(“拆分单词”)时,应将单词放入数组或结构中,并且每个单词都应用循环显示。在此之后,应执行重复删除,程序必须确定重复的单词并消除它们。此后,应再次打印单词列表。
对此的任何帮助将不胜感激。谢谢
这是我的代码,我需要案例“D”方面的帮助
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <string>
#include <algorithm>
#include <cctype>
using namespace std;
int main() {
string s;
char selection;
string w;
cout << "Enter a paragraph or a sentence : ";
getline(cin, s);
int sizeOfString = s.length();
//cout << "The paragraph has " << sizeOfString << " characters. " << endl; ***Dummy call to see if size works.
//cout << "You entered " << s << endl; *** Dummy function !!
cout << "" << endl;
cout << " Menu " << endl;
cout << " ------------------------" << endl;
cout << "" << endl;
cout << "A -- Convert paragraph to all caps " << endl;
cout << "B -- Convert paragraph to all lowercase " << endl;
cout << "C -- Delete whitespaces " << endl;
cout << "D -- Split words & remove duplicates " << endl;
cout << "E -- Search a certain word " << endl;
cout << "" << endl;
cout << "Please select one of the above: ";
cin >> selection;
cout << "" << endl;
switch (selection) //Switch statement
{
case 'a':
case 'A':
cout << "You chose to convert the paragraph to all uppercase" << endl;
cout << "" << endl;
for (int i = 0; s[i] != '\0'; i++) {
s[i] = toupper(s[i]);
}
cout << "This is it: " << s << endl;
break;
case 'b':
case 'B':
cout << "You chose to convert the paragragh to all lowercase" << endl;
cout << "" << endl;
for (int i = 0; s[i] != '\0'; i++) {
s[i] = tolower(s[i]);
}
cout << "This is it: " << s << endl;
break;
case 'c':
case 'C':
cout << "You chose to delete the whitespaces in the paragraph" << endl;
cout << "" << endl;
for (int i = 0; i < s.length(); i++) {
if (s[i] == ' ')
s.erase(i, 1);
}
cout << "This is it: " << s << endl;
break;
case 'd':
case 'D':
cout << "You chose to split the words & remove the duplicates in the paragraph" << endl;
cout << "" << endl;
case 'e':
case 'E':
cout << "You chose to search for a certain word in the paragraph. " << endl;
cout << "" << endl;
cout << "Enter the word you want to search for: ";
cin >> w;
s.find(w);
if (s.find(w) != std::string::npos) {
cout << w << " was found in the paragraph. " << endl;
} else {
cout << w << " was not found in the paragraph. " << endl;
}
}
return 0;
}
【问题讨论】:
-
首先,在比较之前查找
std::tolower和std::toupper以将字符转换为小写或大写(在switch语句中)。例如,在switch语句之前转换您的变量selection。 -
提示:使用
std::vector<std::string>包含您的文字。然后,您可以使用std::sort和std::unique等函数对重复项进行排序和删除。 -
好的,谢谢。我试试看