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

计算某字符出现次数

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

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String str = scanner.nextLine();
        char c = scanner.next().charAt(0);   //输入一个字符
        int res = countc(str, c);
        System.out.println(res);
    }

    public static int countc(String str, char c) {
        // int[] hashChar = new int[26];
        // int[] hashchar = new int[26];
        int count = 0;
        int index1 = c - 'A';  //  B
        int index2 = c - 'a';   //b
        if (index1 >= 0 && index1 <= 25) { //说明字符是大写字母
            for (int i = 0; i < str.length(); i++) {
                if (str.charAt(i) - 'A' == index1 || str.charAt(i) - 'a' == index1) {
                    count++;
                }
            }
        } else if (index2 >= 0 && index2 <= 25) { //说明字符是小写字母
            for (int i = 0; i < str.length(); i++) {
                if (str.charAt(i) - 'A' == index2 || str.charAt(i) - 'a' == index2) {
                    count++;
                }
            }
        }else{
            for (int i = 0; i < str.length(); i++) {   //就是普通数字
                if (str.charAt(i) == c) {
                    count++;
                }
            }
        }

        return count;
    }
}

全部评论

相关推荐

06-23 18:25
沈阳大学 Java
HR已读不回,是我说话方式不对吗?
大白之主:你是串子吗? hr: 我们不招人了,把岗位挂着boss只是因为我闲得慌
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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