第一轮
最后一版(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")
- C++标准库中最直观的获取字符串内部某个字符出现次数的方法是什么?——
count()
。
第二轮
第一版(AC)
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
char c;
getline(cin, s); // basic_string<CharT, Traits, Alloc> &str)
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")
- 如果想不起来用
count()
,自己手搓也是可以的。 tolower(temp) == c || toupper(temp) == c
换成temp == tolower(c) || temp == toupper(c)
也是可以的。- 事实上,写成
temp == tolower(c) || temp == toupper(c)
是更符合题意不容易出错的写法。