题解 | #计算某字符出现次数#

计算某字符出现次数

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()跳过上一行的换行符。

全部评论

相关推荐

08-21 16:35
已编辑
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务