10815 - Andy's First Dictionary

Description

XY学长刚刚立下了再不过CET就直播xx的flag,为了不真的开启直播模式,XY学长决定好好学习英语。于是他每天都读一篇只包含生词的英语文章,并以自己高达450的智商在一秒钟之内记忆下来。

现在给你一篇XY学长今天要读的文章,请你写一个程序,输出他都学习到了哪些单词。
要求:如果文章中有相同的单词,那么仅仅输出一次;而且如果两个单词只有大小写不同,将他们视为相同的单词。

Input

测试数据将输入一篇文章。不超过5000行,每一行最多200个字符,并以EOF结束。

Output

按照字典序输出他学到的单词,每行输出一个单词,输出单词时所有的字母全部小写。 
数据保证最多有5000个需要输出的单词。

Sample Input

样例输入①

a a a a a a a a, a a a a a a.
a a a a b a a a. a? a!!!

样例输入②

Adventures in Disneyland

Two blondes were going to Disneyland when they came to a fork in the
road. The sign read: "Disneyland Left."

So they went home.

Sample Output

样例输出①

a
b

样例输出②

a
adventures
blondes
came
disneyland
fork
going
home
in
left
read
road
sign
so
the
they
to
two
went
were
when

Hint

输入可能包含标点符号,但标点符号显然不能算作单词的一部分。

解题思路:题目中要求只输出新单词而且新单词只输出一次即可,而且按字典序输出即可,自然想到了set容器,set按键值从小到大自动排序,而且自动去重;

AC代码:

代码一:

        刚开始我是用一个字符数组储存,而且字符串函数平常没怎么用过,不太会用,代码写得不好,因为自学的c++,所以c++的string类用的还不太熟练,就没用

#include<iostream>
#include<cstdio>
#include<string>
#include<set>
#include<cstring>
#include<cctype>
using namespace std;
const int maxn=500;
set<string> a;
char *strlwr(char *str)
{
	for(;*str!='\0';str++)
		*str=tolower(*str);
	return str;
 }  
int main()
{
	char b[maxn],c[maxn];
	while(cin>>b)//b储存输入的字符串 
	{
		strlwr(b);//将字符串转换成小写,提交时报错了error: 'strlwr' was not declared in this scope,
					//就是头文件 <cstring>里面的函数啊,不知道为什么报错,我就重新写了下strlwr函数 ,编译通过 
		int n=strlen(b);
		int k=0;
		for(int i=0;i<n;i++)
		{
			if(b[i]<='z'&&b[i]>='a')
			{
				c[k++]=b[i];//如果是字母就储存在数组c中	
			}
			else
			{
				c[k]='\0';
				a.insert(c);//将单词c插入到set容器a中 ,注意c可能为空串,最后输出时判断下 
				k=0;//插入单词后将k重新赋值为0 
			}	
		}
		if(k!=0)//因为如果输入的一个字符串全部为字母时在上面没有加进去,所以在这里加进a中 
		{
			c[k]='\0';
			a.insert(c);
		}
			 
	}
		set<string>::iterator it;
		for(it=a.begin();it!=a.end();it++)//接下来就是输出了 
		{
			if(*it=="")//如果为空串不输出 
			continue;
			cout<<*it<<endl;
		}	
} 

代码二:

仔细看了下c++的string和字符串的相关函数后,发现这道题可以有更简单的写法,而且代码更简洁;

#include <iostream>
#include <string>
#include <set>
using namespace std;
int main()
{
    string s;
    set<string> word;
    while(cin>>s)
    {
    	string c="";//c保存单词,初始化为空串 
        for(int i=0;i<s.size();i++)
        {
            if(isalpha(s[i]))//判断s[i]是不是字母,是的话返回true,否则返回false
                c+=tolower(s[i]);
            else if(c!="")//c为空的时候不能够加入集合,不然会PE
            {
                word.insert(c);
                c="";//将c加入集合后清空c
            }
        }
        if(c!="")//再次判断下不为空,加进去 
            word.insert(c);
    }
    set<string>::iterator it;
    for(it=word.begin();it!=word.end();it++)//用迭代器输出
        cout<<*it<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40707370/article/details/82191658
今日推荐