• Register
Welcome to Kodlogs, programming questions and answer website.
0 votes
11 views

Problem :

How to count the number of occurrences of a character in a string in java
by (6.9k points)  

1 Answer

0 votes

Solution :

Bellow is definitely the fastest way. Regexes are very slow here, and also harder to understand.
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;
}

by (21.9k points)  
edited by
...