George Kastrinis George Kastrinis - 1 month ago 9
Java Question

Simple way to count character occurrences in a string

Is there a simple way (instead of traversing manually all the string, or loop for indexOf) in order to find how many times, a character appears in a string?

Say we have "abdsd3$asda$asasdd$sadas" and we want that $ appears 3 times.

Answer
String s = "...";
int counter = 0;
for( int i=0; i<s.length(); i++ ) {
    if( s.charAt(i) == '$' ) {
        counter++;
    } 
}

This is definitely the fastest way. Regexes are much much slower here, and possible harder to understand.