Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find occurrences of characters in a Java String [duplicate]

Tags:

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?

like image 292
Steffan Harris Avatar asked Sep 21 '10 19:09

Steffan Harris


People also ask

How do you find the occurrence of a character in a string Java?

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.


2 Answers

Guava's CharMatcher API is quite powerful and concise:

CharMatcher.is('a').countIn("aaaab"); //returns 4
like image 106
dogbane Avatar answered Oct 01 '22 19:10

dogbane


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

like image 25
jazzmann76 Avatar answered Oct 01 '22 19:10

jazzmann76