相关知识

  1. 获取字符串中某字符出现次数最简便的方法是什么? 使用std::count(InputIterator first, InputIterator last, const Tp &value)。在这道题中,表现为count(s.begin(), s.end(), c)或者count(s.begin(), s.end(), tolower(c))或者count(s.begin(), s.end(), toupper(c))。如果不用这种方法,就需要自己手搓循环遍历,这样错误的概率就可能增加。

第一轮

最后一版(AC)

#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
using namespace std;

int main() {
    string s;
    char c;
    getline(cin, s);
    cin >> c;

    int result;
    if(isdigit(c) == 1){
        result = count(s.begin(), s.end(), c);
    }else {
        int a = count(s.begin(), s.end(), tolower(c)); 
        int b = count(s.begin(), s.end(), toupper(c));
        result = a + b;
    }

    cout << result << endl;
}
// 64 位输出请用 printf("%lld")

  1. C++标准库中最直观的获取字符串内部某个字符出现次数的方法是什么?——count()

第二轮

第一版(AC)

#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
using namespace std;

int main() {
    string s;
    char c;
    getline(cin, s); 
    cin >> c;

    int count = 0;
    if (isdigit(c)) {
        for (char temp : s) {
            if (temp == c) {
                count++;
            }
        }
    } else {
        for (char temp : s) {
            if (tolower(temp) == c || toupper(temp) == c) {
                count++;
            }
        }
    }

    cout << count;
    return 0;

}
// 64 位输出请用 printf("%lld")

  1. 如果想不起来用count(),自己手搓也是可以的。
  2. tolower(temp) == c || toupper(temp) == c换成temp == tolower(c) || temp == toupper(c)也是可以的。
  3. 事实上,写成temp == tolower(c) || temp == toupper(c)是更符合题意不容易出错的写法。

第三轮

第一版(AC)

#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
using namespace std;

int main() {
    string s;
    getline(cin, s);
    char c;
    cin >> c;

    int count = 0;
    for(char ch : s){
        if(isdigit(c)){
            if(c == ch) count++; 
        }else {
            if(tolower(c) == ch || toupper(c) == ch) count++;
        }
    }

    cout << count << endl;

    return 0;

}
// 64 位输出请用 printf("%lld")

  1. 写这个解法的时候,在纠结先循环还是先选择,最后选择循环里套选择。
  2. 其实,笔者清楚两种思路都是可以的,但想知道哪种写法更不容易出错,或者说,出了错更容易看到和改掉。
  3. 按照第一轮最后一版的思路,在选择里面放循环是更好的选择,即使想不到count()函数,自己封装一个函数也很好,可以增加代码的可读性。
  4. 如果是按照第三轮最后一版的写法,想封装函数就不那么容易,因为不存在结构和功能类似的模块。

第四轮

第一版(AC)

#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
using namespace std;

int main() {
    string s;
    getline(cin, s);
    char c;
    cin >> c;

    int result = 0;
    if(isdigit(c)){
        result = count(s.begin(), s.end(), c);
    }else{
        result = count(s.begin(), s.end(), tolower(c));
        result += count(s.begin(), s.end(), toupper(c));
    }

    cout << result << endl;

    return 0;
}
// 64 位输出请用 printf("%lld")

  1. 这个版本使用了count(),注意用这个函数的时候,给变量起名就不要用count了。