输入一个文本,找出所有不同的单词(连续的字母序列),按字典序从小到大输出。
单词不区分大小写。
样例输入:
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.
样例输出(为了节省篇幅只保留前5行):
a
adventures
blondes
came
disneyland
#include<iostream>
#include<string>
#include<set>
#include<sstream>
using namespace std;
//set里面会自动排序(从小到大)
//tolower()函数是把字符串都转化为小写字母
//touppre()函数是把字符串都转化为大写字母
set<string> dict;//string 集合
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]);//全部转换为小写方便比较大小,在set集合dict中方便自动排序
}
else
{
s[i]=' ';//遇到非字母的字符时,全部变成空格
}
}
stringstream ss(s);//由sstream头文件定义,即将s的值写入ss中
while(ss>>buf)//向buf中写入ss中的值,当传值成功???
{
dict.insert(buf);//向set定义的名为dict的字符串集合写入buf的值 ,并且按照空格分隔它们 ,才可以用下方的方法进行遍历
}
//插入到set集合dict中之后就已经有序的
}
for(set<string>::iterator it = dict.begin();it!=dict.end();++it) //遍历的功能 ,类似于指针
{
cout<<*it<<"\n";//每一个单词都要过行 ,注意前面的*号
}
return 0;
}
关于stringstream的应用:
例子如下:
stringstream sstream;
int first, second;
// 插入字符串
sstream << "456";
// 转换为int类型,因为first是int类型
sstream >> first;//
cout << first << endl;//此时会输出456
// 在进行多次类型转换前,必须先运行clear()
sstream.clear();
// 插入bool值
sstream << true;
// 转换为int类型,因为secong是int类型
sstream >> second;
cout << second << endl;//此时会输出1
本文介绍如何使用C++编程从输入文本中提取并按字典序排序不同单词,不区分大小写。通过示例展示了如何处理字符串、使用set自动排序以及stringstream处理输入流的过程。
622

被折叠的 条评论
为什么被折叠?



