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

计算某字符出现次数

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

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 获取输入的字符串
        String str = in.nextLine();
        // 获取要判断的字符
        String ch = in.nextLine();
        if(str == null){
            return;
        }
        if(ch == null){
            System.out.println(0);
            return;
        }
        // 初始化次数
        int index = 0;

        for(int i = 0; i < str.length(); i++ ){
            if(ch.equalsIgnoreCase(String.valueOf(str.charAt(i)))){
                index++;
            }
        }
        System.out.println(index);
    }
}

用的笨方法,挨个遍历,使用equalsIgnoreCase()方法判断,还要用valueof()方法将char转换为string

全部评论

相关推荐

做个有文化的流氓:不想当将军的士兵不是好士兵
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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