I would like to count the occurrences of a character in a string, suppose I have the string "aaaab", how would i count the amount of a's in it?
In order to find occurence of each character in a string we can use Map utility of Java.In Map a key could not be duplicate so make each character of string as key of Map and provide initial value corresponding to each key as 1 if this character does not inserted in map before.
Guava's CharMatcher API is quite powerful and concise:
CharMatcher.is('a').countIn("aaaab"); //returns 4
String string = "aaab";
int count = string.length() - string.replaceAll("a", "").length();
instead of "a" use a regex like "[a-zA-Z]" to count all word characters
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With