<hdu2072>单词数(set容器,string类应用)

单词数

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 15421    Accepted Submission(s): 4010


Problem Description
lily的好朋友xiaoou333最近很空,他想了一件没有什么意义的事情,就是统计一篇文章里不同单词的总数。下面你的任务是帮助xiaoou333解决这个问题。
 

Input
有多组数据,每组一行,每组就是一篇小文章。每篇小文章都是由小写字母和空格组成,没有标点符号,遇到#时表示输入结束。
 

Output
每组只输出一个整数,其单独成行,该整数代表一篇文章里不同单词的总数。
 

Sample Input
you are my friend #
 

Sample Output
4
 

Author
Lily
 

Source
 

Recommend
linle
                                                         这题使用set容器和string类解决很方便。set容器中元素不重复,于是set中元素个数就是单词数。 参考:http://www.cplusplus.com/reference/stl/set/  AC code:
#include <iostream>
#include <set>
#include <cstdio>
#include <string>
using namespace std;
int main()
{
    set<string>word;
    string s="";
    char c;
    while(scanf("%c",&c) && c!='#')
    {
        if(c==' ')
        {
            if(s.length()) word.insert(s);
            s.clear();//or s=""
        }
        else if(c=='\n' || c=='\r')
        {
            if(s.length()) word.insert(s);
            printf("%d\n",word.size());
            word.clear();
            s.clear();//or s=""
        }
        else
        {
            s+=c;
        }
    }
    return 0;
}

原文地址:https://www.cnblogs.com/cszlg/p/2910507.html