题解 | 计算某字符出现次数
计算某字符出现次数
https://www.nowcoder.com/practice/a35ce98431874e3a820dbe4b2d0508b1?tpId=37&tqId=21225&rp=1&sourceUrl=%2Fexam%2Foj%2Fta%3Fpage%3D1%26tpId%3D37%26type%3D37&difficulty=undefined&judgeStatus=undefined&tags=&title=
#include <iostream>
#include <string>
using namespace std;
int main(){
string s;
char c;
// 读取字符串
getline(cin, s);
// 读取字符
cin >> c;
int count = 0;
// 遍历字符串统计字符出现次数
/* 使用范围for循环替换传统for循环
string s = "Hello";
for(char ch : s) {
cout << ch << " "; // 输出每个字符
}
输出:H e l l o*/
for(char ch : s){
// 如果c是字母
if((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')){
// 统计c的大小写形态出现次数
if(ch == c ||
(c >= 'A' && c <= 'Z' && ch == c + 32) || //在C++编程中,这里的+32和-32是基于ASCII码表的 字符大小写转换运算。在ASCII码表中,大写字母和 小写字母的编码值相差32。具体来说:大写字母A的 ASCII值是65,小写字母a的ASCII值是97,相差32大 写字母B的ASCII值是66,小写字母b的ASCII值是 98,相差32
(c >= 'a' && c <= 'z' && ch == c - 32)){
count++;
}
}
// 如果c是数字
else if(c >= '0' && c <= '9'){
// 统计数字字符出现次数
if(ch == c){
count++;
}
}
}
cout << count;
return 0;
}
