Introduction
Here we will create a simple example to count each character to find out how many times each character repeats in the string. A string can have unique characters as well repeated characters. A string can also have only unique characters in it.
Let’s say, you are given a string input, for example, “Hello World!”. Your output should be, how many times each character is showing up in the string. So, in this example, the output should be, H: 1 e: 1 l: 3 o: 2.
Prerequisites
Java, Eclipse
Counting Characters in String
We will create the following method to count characters in a string. We will put each character as a key in HashMap
and increment it’s counter as a value for the repeated characters.
public static Map<String, Integer> countChars(final String str) {
Map<String, Integer> cMap = new HashMap<>();
for (int i = 0; i < str.length(); i++) {
String s = str.substring(i, i + 1);
if (s == null || " ".equals(s)) {
continue;
}
if (cMap.get(s) != null) {
cMap.put(s, cMap.get(s) + 1);
} else {
cMap.put(s, 1);
}
}
return cMap;
}
Testing the Program
To test the above program create a main method and pass a string as an argument.
public static void main(String[] args) {
Map<String, Integer> cMap = countChars("Hello World");
cMap.forEach((k, v) -> System.out.println(k + " => " + v));
}
The above main method will give you below output:
r => 1
d => 1
e => 1
W => 1
H => 1
l => 3
o => 2
Maintain Order of the Characters
If you want to maintain order of the characters counts while retrieving from the Map
then you can use LinkedHashMap
.
Simple replace the line:
Map<String, Integer> cMap = new HashMap<>();
By
Map<String, Integer> cMap = new LinkedHashMap<>();
The output will be in the order as string:
H => 1
e => 1
l => 3
o => 2
W => 1
r => 1
d => 1
Source Code
Thanks for reading.