题解 | #计算某字符出现次数#
计算某字符出现次数
https://www.nowcoder.com/practice/a35ce98431874e3a820dbe4b2d0508b1
#include <cmath>
#include <iostream>
using namespace std;
int main() {
string s;
while (getline(cin, s)) { // 注意 while 处理多个 case
char c1, c2;
bool isLetter = false;
cin >> c1;
cin.ignore(1);
if (c1 >= 'a' && c1 <= 'z') {
c2 = c1 + 'A' - 'a';
isLetter = true;
} else if (c1 >= 'A' && c1 <= 'Z') {
c2 = c1 + 'a' - 'A';
isLetter = true;
} else {
isLetter = false;
}
int n = 0;
for (char c: s) {
if (c == c1) {
n++;
}
if (isLetter && c == c2) {
n++;
}
}
cout << n << endl;
}
return 0;
}
// 64 位输出请用 printf("%lld")
使用getline()读取一行的话记得用cin.ignore()跳过上一行的换行符。