HihoCoder - 1385 - A Simple Job - string::substr用法总结

題目鏈接

題意:讀入一段文章,算出出現次數最多的詞組。

其實是考察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/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值