使用 count_if 求解
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
int main()
{
    string s;
    getline(cin, s);
    char c = tolower(getchar());
    cout << count_if(s.begin(), s.end(), [c](char i) { return towlower(i) == c; }) << endl;
}
这是我能想到的C++最简单的写法。
#include <iostream>
#include <string>
using namespace std;
int main()
{
    string s;
    getline(cin, s);
    char c = tolower(getchar());
    uint16_t n = 0;
    for (auto i : s) {
        if (tolower(i) == c) {
            ++n;
        }
    }
    cout << n << endl;
}
使用 unordered_map 求解
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
int main(int, char **)
{
    string s;
    char c;
    getline(cin, s) >> c;
    unordered_map<char, size_t> unorderedMap;
    for (auto i : s) {
        ++unorderedMap[tolower(i)];
    }
    cout << unorderedMap[tolower(c)] << endl;
}
变更履历
2022/8/21:新增 count_if 求解 2022/4/9: 新增 unordered_map 求解



 京公网安备 11010502036488号
京公网安备 11010502036488号