查找单词的题目,很有意思,我提供了两个版本

//Exercise
//9.39:
//已知有如下 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 
#include 
#include 
#include 
using namespace std;


int main()
{
   string line1="we are her pride of 10 she named us:";
   string line2="benjamin, phoenix, the  prodigal";
   string line3="and perspicacious pacific suzanen";
   string sentence=line1+" "+line2+" "+line3;
   vector longest_word,smallest_word;
   unsigned int count=0;
   string::size_type s_size_big=0,s_size_small=0;
   string word;
   istringstream in_stream(sentence);
   cout<<"The sentence is :"<>word)
   {
      count++;
      cout<s_size_big)
         {
             s_size_big=size_tmp;
             longest_word.clear();
             longest_word.push_back(word);
         }
         else
         {
            if(size_tmp==s_size_big)
            {
                longest_word.push_back(word);
            }
            else
            {
               if(size_tmp::iterator big_iter=longest_word.begin();big_iter!=longest_word.end();
        big_iter++)
    cout<<*big_iter<<" ";
    cout<::iterator small_iter=smallest_word.begin();small_iter!=smallest_word.end();
        small_iter++)
    cout<<*small_iter<<" ";
    cout<
#include 
#include 
using namespace std;


int main()
{
   string line1="we are her pride of 10 she named us:";
   string line2="benjamin, phoenix, the  prodigal";
   string line3="and perspicacious pacific suzanen";
   string spaces(" \t:,\n\v\r\f");//后面都一些转义字符
   string sentence=line1+" "+line2+" "+line3;
   vector longest_word,smallest_word;
   unsigned int count=0;
   string word;
   string::size_type s_size_big=0,s_size_small=0;
   string::size_type start_pos=0, end_pos=0;
   while((start_pos=sentence.find_first_not_of(spaces,end_pos))!=string::npos)
   {
       ++count;
       string::size_type size_tmp;
       end_pos=sentence.find_first_of(spaces,start_pos); //这个是代码的核心部分
       if(end_pos==string::npos)//如果没有匹配的话就返回npos,这是一个非常大的数,比任何的合法的下标都大
       size_tmp=sentence.size()-start_pos;
       else
       size_tmp=end_pos-start_pos;
       word.assign(sentence,start_pos,size_tmp);
       cout<<"the size of sentence: "<s_size_big)
        


你可能感兴趣的:(C++之初学系列)