/** * Counting the occurrences of a letter in a string * Lots of ways * @author gtowell * Created/Modified: Oct 21, 2021 */ public class Counter { /* * This version is wrong */ public int numOccur1(char ch, String str) { if (str == null || str.equals("")) { return 0; } int count = 0; if (str.charAt(0) == ch) { count++; } numOccur1(ch, str.substring(1)); return count; } int acount = 0; /** * This version works but is bad * @param ch the char to look for * @param str the string to look in * @return count of the char */ public int numOccur2(char ch, String str) { if (str == null || str.equals("")) { return 0; } if (str.charAt(0) == ch) { acount++; } numOccur2(ch, str.substring(1)); return acount; } public int numOccur3(char ch, String str) { if (str == null || str.equals("")) { return 0; } int count = 0; if (str.charAt(0) == ch) { count = 1; } return count + numOccur3(ch, str.substring(1)); } public int numOccur4(char ch, String str) { return numOccur4Util(ch, str, 0); } private int numOccur4Util(char ch, String str, int count) { if (str == null || str.equals("")) { return count; } if (str.charAt(0) == ch) { count++; } return numOccur4Util(ch, str.substring(1), count); } public int numOccur5(char ch, String str) { if (str == null || str.length()==0) return 0; return numOccur5Util(ch, str, 0, 0); } private int numOccur5Util(char ch, String str, int loc, int count) { if (loc >= str.length()) return count; if (str.charAt(loc) == ch) { count++; } return numOccur5Util(ch, str, loc+1, count); } public int numOccur6(char ch, String str) { if (str == null || str.length()==0) return 0; return numOccur6Util(ch, str, 0); } private int numOccur6Util(char ch, String str, int loc) { if (loc >= str.length()) return 0; return (str.charAt(loc)==ch ? 1 : 0) + numOccur6Util(ch, str, loc+1); } public static void main(String[] args) { Counter cc = new Counter(); System.out.println(cc.numOccur5('a', "asdfgfdsawqaw")); } }