C++ Primer 課後習題9.39 統計單詞個數並記錄最大單詞和最短單詞

來源:互聯網
上載者:User

標籤:

習題9.39: 已知有如下string對象:

string line1 = "We were her pride of 10 she named us:";string line2 = "Benjamin, Phoenix, the Prodigal";string line3 = "and perspicacious perspicacious pacific Suzanne";string sentence = line1 + ‘ ‘ + line2 + ‘ ‘ + line3;

編寫程式計算sentence中有多少個單詞,並指出其中最長和最短的單詞。如果有多個最短或者最長單詞,則將他們全部輸出。

代碼:

 1 #include <iostream> 2 #include <vector> 3 #include <list> 4 #include <string> 5 #include <deque> 6 #include <algorithm> 7 #include <sstream> 8 using namespace std; 9 10 int main(int argc, char **argv)11 {    12     string num("0123456789");13     string alpha("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");14     string alphanum = num + alpha;15     string line1 = "We were her pride of 10 she named us:";16     string line2 = "Benjamin, Phoenix, the Prodigal";17     string line3 = "and perspicacious perspicacious pacific Suzanne";18     string sentence = line1 + ‘ ‘ + line2 + ‘ ‘ + line3;19     stringstream ss;20     ss.str(sentence);21     string str;22     string strMax;23     string strMin;24     vector<string> vStrMax;25     vector<string> vStrMin;26     int sum = 0;27     while (ss>>str)28     {29         sum++;30         string::size_type pos = 0;31         //刪除非字母字元32         while ((pos = str.find_first_not_of(alphanum,pos)) != string::npos)33         {34             str.erase(pos);            35         }36         //比較擷取最大單詞37         if (str.size() > strMax.size())38         {    39             strMax = str;40             vStrMax.clear();41             vStrMax.push_back(str);42         }else if (str.size() == strMax.size())43         {            44             vStrMax.push_back(str);            45         }46         //比較擷取最小單詞,注意strMin第一次大小為047         if (str.size() < strMin.size() || strMin.size() == 0)48         {    49             strMin = str;50             vStrMin.clear();51             vStrMin.push_back(str);52         }else if (str.size() == strMin.size())53         {            54             vStrMin.push_back(str);            55         }        56     }57     return 0;58 }

總結:(1)使用字串流處理字串,擷取單個單詞;

   (2)使用string的find_first_not_of()方法除去“,:”非單詞字元。

C++ Primer 課後習題9.39 統計單詞個數並記錄最大單詞和最短單詞

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.