Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)

Can anyone tell me how to find the number of occurrences of a character in a String? 

Below is my example String: 

The quick brown fox jumped over the lazy dog.

See the output as below: 

'a' = 1

'o' = 4

'space' = 8

'.' = 1

1 Answer

0 votes
by (19.7k points)

You can use the below code to count the chars in the String: 

Map<Character,Integer> map = new HashMap<Character,Integer>();

for (int i = 0; i < s.length(); i++) {

  char c = s.charAt(i);

  if (map.containsKey(c)) {

    int cnt = map.get(c);

    map.put(c, ++cnt);

  } else {

    map.put(c, 1);

  }

}

Interested in Java? Check out this Java tutorial by Intellipaat.  

Browse Categories

...