Chinaunix首页 | 论坛 | 博客
  • 博客访问: 162453
  • 博文数量: 30
  • 博客积分: 2010
  • 博客等级: 大尉
  • 技术积分: 290
  • 用 户 组: 普通用户
  • 注册时间: 2008-11-25 19:05
文章分类

全部博文(30)

文章存档

2009年(3)

2008年(27)

我的朋友

分类: C/C++

2009-01-18 20:59:16

统计一句话中单词的以下信息:
单词的总数。
单词中最长的单词的长度,并记录下最长的单词,如果有多个一样最长的单词,则每个都记录下来。
按同样的方式记录最短的单词。
 

#include<string>
#include<iostream>
#include<vector>

using namespace std;
int main()
{
    string line1="We were her pride of 10 she named us:";
    string line2="Benjamin, Phoenix, the Prodigal";
    string line3="and perspicacious1 pacific Suzamme";
    string sentence=line1+" "+line2+" "+line3;
    cout<<sentence<<endl;
    vector<string> maxstr;
    vector<string> minstr;

    string::size_type n1pos=0;
    string::size_type n2pos=0;
    int wl;
    int Maxlen=0;
    int Minlen=10000;
    int k=0;
    string word;

    while ((n1pos=sentence.find_first_of(" ",n1pos))!=string::npos)    {
        k++;
     wl=n1pos-n2pos;
        word=sentence.substr(n2pos,wl);
        if (wl>Maxlen)    {Maxlen=wl; maxstr.clear();maxstr.push_back(word);}
        else if(wl==Maxlen){ maxstr.push_back(word);}

        if(wl<Minlen) {Minlen=wl; minstr.clear();minstr.push_back(word);}
        else if(wl==Minlen){minstr.push_back(word);}
                
        n1pos++;
        n2pos=n1pos;
    }
    cout<<"words numbers:"<<k+1<<endl;
    cout<<"Maxlength:"<<Maxlen<<endl;
    cout<<"Minlength:"<<Minlen<<endl;

    cout<<"Max length words: ";
    for (k=0;k<maxstr.size();k++)
        cout<<maxstr.at(k)<<" ";
    
    cout<<endl<<"Min length words: ";
    for (k=0;k<minstr.size();k++)
        cout<<minstr.at(k)<<" ";

    return 0;
}


输出结果如下:
We were her pride of 10 she named us: Benjamin, Phoenix, the Prodigal and perspicacious1 pacific Suzamme
words numbers:17
Maxlength:14
Minlength:2
Max length words: perspicacious1
Min length words: We of 10 Press any key to continue

 

阅读(1063) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2009-06-30 18:26:45

good!