《primer-c++4》学习笔记-第exercise9.38

来源:互联网 发布:淘宝卖衣服代理 编辑:程序博客网 时间:2024/06/11 15:58

已知有如下 string 对象:
string line1 = "We were her pride of 10 she
named us:";
string line2 = "Benjamin, Phoenix, the
Prodigal"
string line3 = "and perspicacious pacific
Suzanne";
string sentence = line1 + ' ' + line2 + ' ' +
line3;
编写程序计算 sentence 中有多少个单词,并指出其中
最长和最短的单词。如果有多个最长或最短的单词,则
将它们全部输出

#include <iostream>

#include <string>
#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 perspicacious pacific Suzanne";
    string sentence = line1 + ' ' + line2 + ' ' + line3;
     
    string character("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
    vector<string> Maxword,Minword;//记录最长和最短单词的vector容器
    string::size_type count=0,wordlen,maxlen,minlen;//单词总数,当前单词的大小,最长单词的大小,最小单词的大小
    string::size_type pos1=0;//单词的结束位置
    string::size_type pos2=sentence.find_first_of(character);//单词的开始位置

    pos1=sentence.find_first_not_of(character,pos1);
    if(pos1==string::npos)
        wordlen=sentence.size()-pos2;
    else
        wordlen=pos1-pos2;
    string word;
    word.assign(sentence,pos2,wordlen);//获取第一个单词
    maxlen=minlen=wordlen;
    Maxword.push_back(word);
    Minword.push_back(word);
    ++count;
 //依次处理后面的单词
     while((pos2=sentence.find_first_not_of(character,pos1))!=string::npos)
     {
         ++pos2;
         pos1=sentence.find_first_not_of(character,pos2);
         if(pos1==pos2)
             ;
         else
         {
             ++count;
             if(pos1==string::npos)
                wordlen=sentence.size()-pos2;
                else
                wordlen=pos1-pos2;

            word.assign(sentence,pos2,wordlen);
             if(wordlen>maxlen)
             {    
                 maxlen=wordlen;
                 Maxword.clear();
                 Maxword.push_back(word);
             }
             else if(wordlen==maxlen)
                 Maxword.push_back(word);

             if(wordlen<minlen)
             {    
                 minlen=wordlen;
                 Minword.clear();
                 Minword.push_back(word);
             }
             else if(wordlen==minlen)
                 Minword.push_back(word);
         }

     }

//输出
     cout<<"the count of words :"<<count<<endl;
     vector<string>::iterator item;
     cout<<"the longest words :"<<endl;
     item=Maxword.begin();
     while(item!=Maxword.end())
         cout<<*item++<<endl;

     cout<<"the shortest words :"<<endl;
     item=Minword.begin();
     while(item!=Minword.end())
         cout<<*item++<<endl;
     return 0;
}

0 0
原创粉丝点击