Search code examples
javastring

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 to know that $ appears three times.


Solution

  • 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 possibly harder to understand.