Simple way to count character occurrences in a string [duplicate]

public int countChar(String str, char c)
{
    int count = 0;

    for(int i=0; i < str.length(); i++)
    {    if(str.charAt(i) == c)
            count++;
    }

    return count;
}

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

Leave a Comment