Sample Input

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

adventures

blondes

came

disneyland

fork

going

home

in

left

read

road

sign

so

the

they

to

two

went

were

when

 

题意:把一个文本域的单词按字典序排序。

分析:用了set的唯一性和自动排序性,用了stringstream来处理流。

附上string和char[] 的比较:

操作 string 字符数组
定义字符串 string s; char s[100];
取得第i个字符 s[i] s[i]
字符串长度 s.length()
或 s.size()
strlen(s)
读入一行 getline(cin, s); gets(s);
赋值 s = "you"; strcpy(s, "you");
字符串连接 s = s + "you";
s += "you";
strcat(s, "you");
字符串比较 s == "you" strcmp(s, "you");

 

其中stringstream ss(s) 读取s中的单字,比如hello world ,就会读取hello和world。创建存储s的副本的 stringstream 对象,其中s是 string 类型的对象.

贴代码:

#include <iostream>
#include <string>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <ctime>
#include <vector>
#include <set>
#include <sstream>
using namespace std;
#define Start clock_t start = clock();
#define End clock_t end = clock();
#define Print cout<<(double)(end-start)/CLOCKS_PER_SEC*1000<<"毫秒"<<endl;
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);
        while(ss >> buf) dict.insert(buf);
    }
    for(set<string>::iterator it = dict.begin();it != dict.end();++it)
        cout<<*it<<endl;

    return 0;
}