Count occurences of a String in another String in Java using Apache Commons



Here is a small example of how to count character sequences within a String using the Apache Commons StringUtils class.
The StringUtils class comes with a method countMatches() which takes two parameters, the String to analyze and the substring or sequence of characters to look for.
The method is case-sensitive so even if we have two occurences of the word ‘the’ below the method will only find one since the other is capitalized:

However, we can use the standard Java String-method toLowerCase if we want to ignore case:







Search for more Java info on this site here:
Custom Search


Please type any questions here.