习题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第一次大小为0 47 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()方法除去“,:”非单词字符。