Andy’s First Dictionary(安迪的第一部词典)

本文介绍了一个编程解决方案,利用C++编写程序,通过逐行读取输入的故事书文本,将所有不重复的单词(忽略大小写)按字母顺序排列并输出。使用了stringstream处理单词并存储在set中,实现高效去重和排序。
摘要由CSDN通过智能技术生成

题目:

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;
}



    }
}

 

 

 

 

 

 

 

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

亦木不emo

打赏一个吧亲

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值