I am trying to write a for loop in Java that will count the occurrences of a letter in a string. The user will enter the letter to count and the string in which to search. This
No need to loop:
String sentence = "abcabcabcd"; String letter = "b"; int numOfOccurences = sentence.length() - sentence.replaceAll(letter, "").length(); System.out.println("numOfOccurences = "+numOfOccurences);
OUTPUT:
numOfOccurences = 3