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

计算某字符出现次数

https://www.nowcoder.com/practice/a35ce98431874e3a820dbe4b2d0508b1

#include <iostream>

bool sameLetter(char c1, char c2)
{
    int id1{static_cast<int>(c1)};
    int id2{static_cast<int>(c2)};
    if (id1 > 64 && id2 > 64 && id1%32-1 <=26 && id1%32 == id2%32)
        return true;
    // convert into ASIC II value for matching upper case letter with lower case letter.

    return (c1 == c2);
}

int main() {
    std::string s{};
    char c{};
    std::getline(std::cin >> std::ws, s);
    std::cin >> c;

    int num{};
    for (char ch: s)
        if (sameLetter(ch, c)) num++;

    std::cout << num;
    return 0;
}
// 64 位输出请用 printf("%lld")

使用ASIC II 表,判断输入是否均为字母:

  • 如果不是,直接比较。
  • 如果均为字母,转换为代码,比如 "A" 和 "a" 都代表1, "Z"代表26。

循环采用 ranged for loops;std::getline(std::cin >> std::ws, s);用于一次获取所有输入但忽略换行符号。

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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