George Kastrinis George Kastrinis - 5 months ago 29
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.

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

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