Andy's First Dictionary

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

没有什么技巧,熟悉一下set和stringstream用法。

#include<iostream>
#include<sstream>
#include<set>
using namespace std;

set<string> dict;

int main()
{

    string s,buff;

    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);
        while(ss >> buff){
            dict.insert(buff);
        }
    }

    set<string>::iterator iter = dict.begin();
    for(; iter != dict.end(); iter++){
        cout << *iter << endl;
    }
    return 0;

}

stringstream的基本用法

stringstream是字符串流。它将流与存储在内存中的string对象绑定起来。
在多种数据类型之间实现自动格式化。

1.stringstream对象的使用

#include<sstream>
#include<iostream>
using namespace std;
int main()
{
        string line,word;
        while(getline(cin,line))
        {
                stringstream stream(line);
                cout<<stream.str()<<endl;
                while(stream>>word){cout<<word<<endl;}
        }
        return 0;
}

输入:shanghai no1 school 1989
输出:shanghi no1 school 1989
   shanghai
    no1
    school
    1989

2.stringstream提供的转换和格式化
程序:

#include<sstream>
#include<iostream>
using namespace std;
int main()
{
        int val1 = 512,val2 =1024;
        stringstream ss;
        ss<<"val1: "<<val1<<endl          //“val1: "此处有空格,字符串流是通过空格判断一个字符串的结束
     <<"val2: "<<val2<<endl;
        cout<<ss.str();

        string dump;
        int a,b;
        ss>>dump>>a
     >>dump>>b;
        cout<<a<<" "<<b<<endl;
        return 0;
}

输出为:val1: 512
    val2: 1024
    512 1024
第一处黑体字部分:将int类型读入ss,变为string类型
第二处黑体字部分:提取512,1024保存为int类型。当然,如果a,b声明为string类型,那么这两个字面值常量相应保存为string类型

3.其他注意
stringstream不会主动释放内存(或许是为了提高效率),但如果要在程序中用同一个流,反复读写大量的数据,将会造成大量的内存消耗,
因些这时候,需要适时地清除一下缓冲 (用 stream.str(“”) )

#include <cstdlib>
#include<iostream>
#include<sstream>
using namespace std;
int main()
{
        stringstream ss;
        string s;
        ss<<"shanghai no1 school";
        ss>>s;
        cout<<"size of stream = "<<ss.str().length()<<endl;
        cout<<"s: "<<s<<endl;
        ss.str("");
        cout<<"size of stream = "<<ss.str().length()<<endl;
}

输出:
size of stream = 19
s: shanghai
size of stream = 0

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值