This example will count the occurrences of a character in string using java, java 8, guava, apache commons and spring framework. Each snippet will use the phrase "she saw a fish on the seashore and I'm sure The fish she saw on the seashore was a saw-fish." and count the number of 'a' that exist. In a comparable illustration we demonstrate how count the number of characters in string using groovy.
Straight up Java
Using a straight up java technique we count the number of letters in specified string by iterating over each string index and checking if it equals the letter 'a'.
This snippet shows one way to count the number of times a letter occurs in a string with guava. There is an open issue to create a new method Strings.count(String string, String substring). Using guava Splitter we will split the string on the letter 'a' which will return an Iterable of elements. Then to find the count we will call Iterable.size which return 15.
This snippet will counts how many times a string appears in another string with apache commons by using StringUtils.countMatches.
Springframework StringUtils.countOccurrencesOf will also count the occurrences of the substring in stringToSearch.