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

计算某字符出现次数

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;
}

全部评论

相关推荐

饿魔:看到在线简历了吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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