18、統計單詞
問題描述 :
實驗目的:string、vector、類的綜合應用。
實驗內容:
從鍵盤輸入一篇文章,統計其中單詞出現的次數(不區分大小寫),並輸出出現次數排名第一的單詞及其次數。注意:可能有多個單詞並列第一,需要全部輸出。輸出時,如果有多個單詞排名並列,則按其在文章中出現的先後順序輸出,先出現的先輸出。
說明:為簡單起見,單詞的含義是空白字元分隔開的連續字串。比如“I love China!”這句話包含三個單詞,第三個單詞是“China!”(包括其中的感嘆號),再如“Hi !”,這句話包含兩個單詞,第二個單詞僅為一個感嘆號。
參考以下main函式:
int main()
{
vector<WordCount> vwc;
string str;
int i;
while(cin>>str)
{
str = ToLower(str);
CountWord(vwc, str);
}
DisplayResult(vwc);
return 0;
}
其中:
-
WordCount類:儲存單詞及其出現次數
-
ToLower函式:傳入一個字串,將其中大寫英文字母轉換為小寫、其餘字元保持不變,返回轉換後的結果。
-
CountWord函式:傳入一個vector和一個單詞,在vector中查詢該單詞是否已存在(注意:vector中的元素為WordCount物件,該物件有一個屬性為單詞字串),如果已存在,則將其出現次數加1,否則在vector中新增一個元素(WordCount物件),該元素儲存這個新的單詞及其出現次數(此時為1)。
-
DisplayResult函式:傳入一個vector,輸出其中出現次數最高的單詞及其次數。
請實現以上定義的WordCount類及三個函式。
輸入說明 :
輸入一篇文章,其中包含可見字元及空白字元(可能有換行)。
輸出說明 :
每個單詞佔一行,如果有n個單詞,則輸出n行,
每行首先輸出單詞(以小寫字母形式輸出),然後輸出一個空格,再輸出單詞的出現次數。
單詞輸出的順序按照在文章中出現的先後順序。
輸入範例 :
abc Abc, ABC.
abc!
abc, def
DEf
輸出範例 :
abc, 2
def 2
題解程式碼:
#include<iostream> #include<cstdio> #include<cstdlib> #include<cmath> #include<cstring> #include<string> #include<map> #include<algorithm> #include<set> #include<vector> #include<queue> using namespace std; class WordCount { public: string s; int n; WordCount(); WordCount(string sr); }; WordCount::WordCount() { n = 0; s.clear(); } WordCount::WordCount(string sr) { s = sr; n = 1; } string ToLower(string s) { string s1; int i = 0; for (i = 0; i < s.size(); i++) if ('A' <= s[i] && s[i] <= 'Z') s[i] += 32; return s; } void CountWord(vector<WordCount>& a,string word) { int i; bool ok = 0; word = ToLower(word); for(i=0;i<a.size();i++) if (a[i].s == word) { ok = 1; a[i].n++; break; } if (ok == 0) { WordCount z(word); a.push_back(z); } return; } void DisplayResult(vector<WordCount> a) { int huge = -1; int i; for (i = 0; i < a.size(); i++) { if (a[i].n > huge) huge = a[i].n; } for (i = 0; i < a.size(); i++) { if (a[i].n == huge) { cout << a[i].s << " " << a[i].n << endl; } } return; } int main() { vector<WordCount> vwc; string str; int i; while (cin >> str) { str = ToLower(str); CountWord(vwc, str); } DisplayResult(vwc); return 0; }