Back
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
'a' = 1
'o' = 4
'space' = 8
'.' = 1
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); }}
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.
31k questions
32.8k answers
501 comments
693 users