单词计数 soj1076

                                        BlueEyes' Problem

The Problem

袁源在学英语的时候遇到了一个难题。当他看到一个单词的时候,他不知道这个词他以前是否背过。(这种事也常发生在其他人身上)。为了解决这个问题,他想在读某篇文章之前,先统计这篇文章中每个单词出现的次数。如果是你,你会怎么实现'统计'这个过程呢?

输入

本题只有一组数据.输入为一篇不换行的英语文章(包括各种常用符号,长度小于10000个字母).'单词'在这里定义为只包含52个大小写字母的连续字符串(大写和小写是不同的字母,每个单词的长度不超过100,整个文章总共的单词数不超过1000个,如I'll是两个单词:'I'和'll').符号'@'标志文章的结束.

输出

输出每行包括一个单词本身以及它在文章中出现的次数,中间用一个空格隔开.单词按出现的先后顺序排列.

样例输入

Sometimes I do things I want to do,the rest of time I do things I have to.@

样例输出

Sometimes 1
I 4
do 3
things 2
want 1
to 2
the 1
rest 1
of 1
time 1
have 1

题意很清楚:给出一个字符串,找出其中所有的单词以及该单词出现的次数。一开始想到用map直接去实现,但是到后面发现输出结果的时候顺序不对,因为map是基于红黑树实现的,在进行插入时就是自动按照键值进行自增排序的,因此后来换用结构体实现。

 

#include<iostream>
#include<string>
#include<ctype.h>
#include<algorithm>
usingnamespace std;

typedef struct node
{
    string word;
    int times;
}Node;

Node t[1010];
int num=0;

int Search(string str) //查找该单词是否已经出现过
{
    int i;
    for(i=0;i<num;i++)
    {
        if(t[i].word==str)
            return i;
    }
    return i;
}

int main(void)
{
    int i=0,j=0,k;
    string s;
    char ch;
    while((ch=getchar())!='@')
    {
        s+=ch;
    }
    while(i<s.length())
    {
        string temp;
        if(isalpha(s[i]))
        {
            j=i;
            while(isalpha(s[j])&&j<s.length())
            {
                temp+=s[j];
                j++;
            }
            k=Search(temp);
            if(k==num) //如果该单词没有出现过
            {
                t[num].word=temp;
                t[num].times=1;
                num++;
            }
            else
            {
                t[k].times++;
            }
            i=j;
        }
        else
        {
            i++;
        }
    }
    for(i=0;i<num;i++)
    {
        cout<<t[i].word<<""<<t[i].times<<endl;
    }
    return0;
}

 

 

 

posted @ 2011-04-16 16:30  Matrix海子  阅读(898)  评论(0编辑  收藏  举报