1、使用String.charAt()和substring()实现
public class Main { public static void main(String[] args) { System.out.println(numberOf("https://www.cjavapy.com", 'a')); } static int numberOf(String text, char characterToCount) { if (text.isEmpty()) { return 0; } if (text.charAt(0) == characterToCount) { return numberOf(text.substring(1), characterToCount) + 1; } return numberOf(text.substring(1), characterToCount); } }
2、使用String.length()和String.charAt()实现
public class Main { public static void main(String[] args) { System.out.println(numberOf("https://www.cjavapy.com", 'a')); } static int numberOf(String text, char ch) { if (ch >> 8 >= text.length()) { return 0; } if (text.charAt((ch >> 8)) == (ch & 0xff)) { return numberOf(text, (char)(ch + 256)) + 1; } return numberOf(text, (char)(ch + 256)); } }
或者
public class Main { public static void main(String[] args) { System.out.println(numberOf("https://www.cjavapy.com", 'a')); } static int numberOf(String text, char characterToCount) { return helper(text, characterToCount, 0); } static int helper(String text, char charToCount, int index) { if (text.isEmpty() || index == text.length()) return 0; int countCharOnRight = helper(text, charToCount, index+1); return (text.charAt(index) == charToCount) ? 1 + countCharOnRight : countCharOnRight; } }