標籤:
習題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 統計單詞個數並記錄最大單詞和最短單詞