题目:在给定字符串中找出单词( “单词”由大写字母和小写字母字符构成,其他非字母字符视为单词的间隔,如空格、问号、数字等等;另外单个字母不算单词);找到单词后,按照长度进行降序排序,(排序时如果长度相同,则按出现的顺序进行排列),然后输出到一个新的字符串中;如果某个单词重复出现多次,则只输出一次;如果整个输入的字符串中没有找到单词,请输出空串。输出的单词之间使用一个“空格”隔开,最后一个单词后不加空格。
考查内容:STL的熟悉程度
代码:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <stack>
using namespace std;
bool isshorter(const string &s1,const string &s2)
{
return s1.size() < s2.size();
}
bool test(string::iterator i)
{
if ((*i <= 'z'&&*i >= 'a') || (*i <= 'Z'&&*i >= 'A'))
return true;
else
return false;
}
string creatstring(deque < char > &d)
{
string temp = "";
while (!d.empty())
{
temp += d[0];
d.pop_front();
}
return temp;
}
int main()
{
string src,temp;
vector<string> result;
deque < char > cd;
getline(cin, src);
for (auto begin = src.begin(), end = src.end(); begin != end; ++begin)
{
if (test(begin))
cd.push_back(*begin);
else
{
temp = creatstring(cd);
if (temp.length() > 1)
result.push_back(temp);
}
}
temp = creatstring(cd);
if (temp.length() > 1)
result.push_back(temp);
stable_sort(result.begin(), result.end(),isshorter);
auto f=unique(result.begin(), result.end());
for (auto begin = result.begin(); begin != f; ++begin)
{
cout << *begin;
if (begin != f - 1)
cout << " ";
}
}