题解 | #计算某字符出现次数#
计算某字符出现次数
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
