题解 | #计算某字符出现次数#
计算某字符出现次数
https://www.nowcoder.com/practice/a35ce98431874e3a820dbe4b2d0508b1
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string a; //[1]
getline(cin,a);
char b;
cin>>b;
b=tolower(b); //[2]
int num=0;
for(auto i:a){ // Traverse the input string and count occurrences of the target character
if(tolower(i) == b)
num++;
}
cout<<num<<endl;
return 0;
}
[1] std::string inputString;:用于存储整行输入字符串。
char targetChar;:用于存储单个字符。std::getline(std::cin, inputString);:读取整行字符串。std::cin >> targetChar;:读取单个字符。[2] std::tolower 是 C 和 C++ 标准库中的一个函数,用于将一个字符转换为其对应的小写字母形式。它定义在 <cctype> 头文件中。函数 std::toupper,用于将一个字符转换为其对应的大写字母形式。它定义在 <cctype> 头文件中。
islower()是 C 和 C++ 标准库中的一个函数,用于检查一个字符是否是小写字母。它定义在<cctype>头文件中。