題意:讀入一段文章,算出出現次數最多的詞組。
其實是考察std::map的運用。其實也考察std::string::substr的運用。
實現如下:
#include<bits/stdc++.h>
#define msi map<string,int>
#define fi first
#define se second
using namespace std;
msi m;
void process(int from, string &s) {
if(from > s.size()) return;
int i;
for(i = from; i < s.size(); i++) {
if(s[i] == ',' || s[i] == '.') break;
}
stringstream ss(s.substr(from, i - from));
vector<string> v;
string temp;
while(ss >> temp) {
v.push_back(temp);
}
for(int j = 1; j < v.size(); j++) {
temp = v[j - 1] + " " + v[j];
m[temp]++;
}
return process(i + 1, s);
}
int main() {
#ifdef LOCAL
freopen("in.txt", "r", stdin);
#endif
string s;
while(getline(cin, s)) {
if(s == "####") {
string temp;
int times = 0;
for(msi::iterator it = m.begin(); it != m.end(); it++) {
int this_times = it->se;
if(this_times > times) {
times = this_times;
temp = it->fi;
}
}
cout << temp << ":" << times << endl;
m.clear();
} else {
process(0, s);
}
}
return 0;
}
我在這裏總結一下string.substr函數的運用。
#include<iostream>
#include<string>
using namespace std;
int main() {
string test = "012345";
// substr依據接受參數數目不同分爲兩種。
// 返回值爲string類型。
cout << test.substr(3,100) << endl;
// 返回從下標爲3 即test[3]開始 長度爲100的子串。輸出 "345"。
// 很明顯,沒有這麼長的子串。所以默認只取到串尾。不會報錯。
// 開始位置也包括在內。
cout << test.substr(3) << endl;
// 返回從下標3開始一直到串尾的字串。輸出 "345"。
cout << test.substr(6) << endl;
// 返回從下標6開始一直到串尾的字串。是個空字符串。所以只能看到換行的效果。
// 不會報錯。
cout << test.substr(7) << endl;
// 一旦輸入的下標超過了 test 的長度(即test.size() 或者 test.length())即超過test.end()對應的位置,就會報越界錯誤。
return 0;
}
參考文獻:
std::string::substr - cpp reference: http://www.cplusplus.com/reference/string/string/substr/