题解 | #计算某字符出现次数#
计算某字符出现次数
https://www.nowcoder.com/practice/a35ce98431874e3a820dbe4b2d0508b1
#include <iostream> #include <string> int main() { std::string input; std::getline(std::cin, input); char ch; std::cin >> ch; int case_diff = 'a' - 'A'; int cnt = 0; for (char c : input) { if (c == ch) { cnt++; } else if (c <= 'z' && c >= 'a' && c == ch + case_diff) { cnt++; } else if (c <= 'Z' && c >= 'A' && c == ch - case_diff) { cnt++; } } std::cout << cnt << std::endl; }
- 使用getline获取喊空格的字符串
- 当与输入字符不相等时,需要进一步判断当前字符是否大小写
- 不建议先转大小写再判断,那样需要循环两次