我正在创建一个包含string sentence
或paragraph
的程序。
我对使用std不太熟悉::
我不是要求某人为我做这件事,我只是想看看是否有人可以告诉我一个这方面的例子。
当选择第4个选项(“Split Words”)时,应将单词放入数组或结构中,并且每个单词应显示loop
。在此之后,应执行重复删除,程序必须确定重复的单词并消除它们。在此之后,应再次打印单词列表。
对此的任何帮助将不胜感激。谢谢
代码:(我需要案例帮助' 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;
}
答案 0 :(得分:1)
编写解析字符串 s 中的单词的代码(这里有一个方法:Split a string in C++?)。在解析它们时打印单词,然后将它们放在某种 set 容器中。 设置容器不允许重复。完成解析单词后,迭代集并打印出单词(不会重复)。
如果您需要按照字符串中出现的顺序打印出去掉的单词,那么您可以在集合旁边保留向量。像以前一样,当您解析单词时,将它们添加到集合,但是从集合的 insert()方法中检查返回的对(它可以告诉您是否插入的项目对于集合是新的,或者如果插入操作被拒绝,因为该集合已经包含一个等于您尝试插入的值的值:http://www.cplusplus.com/reference/set/set/insert/)。
std:vector<std:string> wordVector; // Assume populated with raw parsed words
std:set<std:string> deDupedSet;
std:vector<std:string> deDupedVector;
for (int i = 0; i < wordVector.size(); i++)
{
if (deDupedSet.insert(wordVector[i]).second())
{
deDupedVector.push_back(wordVector[i]);
{
}
// Print the deDupedVector afterwards