题解 | 计算某字符出现次数
计算某字符出现次数
https://www.nowcoder.com/practice/a35ce98431874e3a820dbe4b2d0508b1
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
string str; //字符串变量
char c; //标志位
getline(cin, str); //读取一整行
cin >> c;
int count = 0; //统计器
//判断输入的c是不是字母 isalpha是C++标准库中的函数,用于判断参数是否是英文字母
if (isalpha(c)) {
char low = tolower(c); //存储小写字母
char up = toupper(c); //存储大写字母
//定义ch存储循环str的结果
for(char ch : str){
if (ch == low || ch == up) count++;
//++count;
}
}else {
//不是字母是数字
for(char ch : str){
if (ch == c) count++;
//++count;
}
}
cout << count << '\n';
return 0;
}

