Title

UVA10815 安迪的第一个字典 Andy's First Dictionary

UVA10815 安迪的第一个字典 Andy's First Dictionary

题目描述(..)

PDF

img

输入格式

img

输出格式

img

题意翻译

输入一个文本,找出所有不同的单词(连续的字母序列),按字典序从小到大输出,单词不区分大小写。

输入输出样例

输入 #1复制

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.

输出 #1复制

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

代码(融入set)

#include<iostream>
#include<sstream>
#include<set>
using namespace std;
int main()
{
	set<string> dict;
	string s,final;
	while(cin>>s)
	{
		//转小写,对应的是题目中的不区分大小写 
		for(int i=0;i<s.length();i++)
		{
			if(isalpha(s[i]))
			   s[i]=tolower(s[i]); 
			else 
			   s[i]=' ';   
		}
		
		stringstream stream(s);
		while(stream>>final)
		dict.insert(final); 
//		cout<<"当前集合内共有"<<dict.size()<<"个元素"<<endl; 
//       cout<<"当前集合中第一个元素是:"<<*dict.begin()<<endl;
//		cout<<"当前集合中a的个数是:"<<dict.count("a")<<endl;
//	    set<string>::iterator it = dict.end();
//	    it--;
//	    cout<<"当前集合中最后一个元素是:"<<*it<<endl;
	}
	
	for(set<string>::iterator it = dict.begin();it!=dict.end();it++)
	{
		cout<<*it<<endl;//输出迭代器指向的内容 
	}
}

坑点

  • while(stream>>final)

    代码中有些操作会把字符串的中间部分变成空格段,从而切分成多个字符串,如果没用while,一次只能弹出一个符合规格的字符串

    "hello666world"会变成"hello  world"
    
  • 容器.end()指向的是最后一个元素的下一个位置。

stringstream的初步应用

#include<iostream>
#include<sstream>
using namespace std;
int main()
{
	string s;
	//stringstream stream;//简单定义一个叫stream的stringstream类型;
	cin>>s;
	int n;
	stringstream stream(s);//将s这个字符串导入到一个叫stream的stringstream的类型中去
    stream>>n;//将stream内的内容(字符串变量)导入到整型变量n中
    cout<<n;
    return 0;
}

input1

55566aaa22

output1

55566

input1

a55566aaa22

output1

0
  • 注意stringstream在再次使用的时候要加上stringstream名.clear()对其进行清空来做重置处理,然后再做流入操作。
posted @ 2021-04-08 14:03  BeautifulWater  阅读(131)  评论(0编辑  收藏  举报