题目:
Description
Andy, 8, has a dream - he wants to produce his very own dictionary. This is not an easy task for him, as the number of words that he knows is, well, not quite enough. Instead of thinking up all the words himself, he has a briliant idea. From his bookshelf he would pick one of his favourite story books, from which he would copy out all the distinct words. By arranging the words in alphabetical order, he is done! Of course, it is a really time-consuming job, and this is where a computer program is helpful.
You are asked to write a program that lists all the different words in the input text. In this problem, a word is defined as a consecutive sequence of alphabets, in upper and/or lower case. Words with only one letter are also to be considered. Furthermore, your program must be CaSe InSeNsItIvE. For example, words like “Apple”, “apple” or “APPLE” must be considered the same.
你需要写一个程序去列出输入文本的所有单词,问题中的单词定义为连续的字母序列,大写或小写。只有一个字母的单词也要考虑。此外,你的程序必须CaSe InSeNsItIvE,例如,“Apple” “apple” “APPLE”都被看作一个单词。
思路:
将字符全部转换成小写存入set中,由set自动排序并去重,再顺序输出即可。
其中判断大小写用到is alpha(),大写转化成小写用到tolower(),同时用到stringstream将单词存入set容器中。
stringstream 是 C++ 提供的另一个字符串型的输入输出流,和iostream 类似。在这里使用它可以用空格键来分割字符,从而将单词一个个存入set。
代码:
直接上标程:
#include<bits/stdc++.h>
using namespace std;
const int mod=1e9+7;
set<string>dict;
int main()
{
string s,buf;
while(cin>>s)
{
for(int i=0; i<s.length(); i++)
{ //找到字母,然后都变成小写字母,不是字母的变成空格
if(isalpha(s[i]))s[i]=tolower(s[i]);
else s[i]=' ';
}
stringstream ss(s); //都存入set里面
while(ss>>buf)dict.insert(buf);
}
//遍历set
for(set<string>::iterator it=dict.begin(); it!=dict.end(); it++)
{
cout<<*it<<endl;
}
return 0;
}
}
}