/* * 题目分析: 获取字符串中指定字符的数量 * 解题思路: 遍历字符串就可以了 * 注意事项: * 1. 该题不区分大小写,字符大小写转换: Character.toLowerCase('A') * 2. Exception in thread "main" java.util.InputMismatchException -- 用nextInt接收第二行的字母导致 * 其它解法: (参考其他答案) 使用 replace() 方法将 指定字符 替换为空字符串 "" 后得到新字符串, 旧字符串减去新字符串的长度即指定字符的数量 */ import java.util.Scanner; public class Main { public static void main(String args[]) { Scanner sc = new Scanner(System.in); String str = sc.nextLine().toLowerCase(); int len = str.length(); char ch = Character.toLowerCase(sc.nextLine().charAt(0)); int cnt = 0; for (int i = 0; i < len; i++) { if (str.charAt(i) == ch) { cnt++; } } System.out.print(cnt); } }