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

计算某字符出现次数

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);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            String s = in.nextLine();
            String c = in.nextLine();

            char cCharValue = c.charAt(0);
            int resultNum = 0;
            if (Character.isLetter(cCharValue)){ // 是字母

                resultNum = letterNum(s,cCharValue);

            } else if(Character.isDigit(cCharValue)){ // 数字

                resultNum = digitNum(s,cCharValue);
 
            }

            System.out.println(resultNum);
        }
    }

    private static int letterNum(String s, char c){

      int resultNum = 0;
      for(int i = 0 ; i < s.length() ; i++){
            
            if(c == s.charAt(i) || 
               c == s.toUpperCase().charAt(i) || 
               c == s.toLowerCase().charAt(i) 
               ) {
               resultNum ++;
            }
 
      }
 
       return resultNum;

    }

    private static int digitNum(String s, char c){
      int resultNum = 0;
      for(int i = 0 ; i < s.length() ; i++){
            
            if(c == s.charAt(i)) {
               resultNum ++;
            }
 
      }
       


       return resultNum;

    }


}

全部评论

相关推荐

喵_coding:年底缺人是短视频营造出来的 而且一般说的也很宽泛 不是特指后端
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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