题解 | 计算某字符出现次数
计算某字符出现次数
https://www.nowcoder.com/practice/a35ce98431874e3a820dbe4b2d0508b1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNext()) { // 注意 while 处理多个 case
String a = in.nextLine();
String b = in.nextLine();
int count = countNum(a, b);
System.out.println(count);
}
}
public static int countNum(String a, String b) {
String regex = "^[A-Za-z0-9]+$";
Pattern pattern = Pattern.compile(regex);
Matcher m = pattern.matcher(b);
if (a == null || a.isEmpty() || b == null || b.isEmpty() ||
a.length() < b.length() || b.length() != 1 || !m.matches()) {
return 0;
}
int count = 0;
for(int i=0;i<a.length();i++){
if((a.subSequence(i,i+1)+"").equalsIgnoreCase(b)){
count ++;
}
}
return count;
}
}