Java Program to find occurrence of a character in a string

To find the occurrence of a character in a string, we can use Java program. the program stores the occurrence count and compare it with the ASCII value of the particular character. For example, if the ASCII value of A is 65, its value will be stored in array counter[65]. This process then moves to creating another array where we store together the character of the given string. Then we compare them with each other in the string. As a result, we find a match. It can be displayed using the first counter array as how many times have the character appeared.

Learn Java String IndexOf Method

The occurrence of a character in a string can be found using several ways:

We can use a hashmap. In this process, we can create a hashmap in Java(char,int). Then we traverse the hashmap in the string. We will check if the character is already present in the hashmap or not. If yes, we will increase the counter. We can do the increment using get() and put() functions. When the traversal is over, we print the output which is how many time a character has appeared in the string.

Below is a program of how to use hashmap to find occurrence of a character in a string:

import java.util.HashMap;
public class EachCharCountInString
{
private static void characterCount(String inputString) {
HashMap<Character, Integer> charCountMap = new HashMap<Character, Integer>();
char[] strArray = inputString.toCharArray();
for (char c : strArray) {
if(charCountMap.containsKey(c)) {
charCountMap.put(c, charCountMap.get(c)+1);
}
else{
charCountMap.put(c, 1);
}
}
System.out.println(inputString+" : "+charCountMap);
}
public static void main(String[] args) {
characterCount("My name is Megha");
characterCount("Welcome to Developer helps");
characterCount("We provide you solutions");
}
}

The output of the above program in Java will be:

My name is Megha : { =3, a=2, s=1, e=2, g=1, h=1, y=1, i=1, M=2, m=1, n=1}
Welcome to Developer helps : { =3, c=1, D=1, e=6, h=1, l=3, m=1, o=3, p=2, r=1, s=1, t=1, v=1, W=1}
We provide you solutions : { =3, d=1, e=2, i=2, l=1, n=1, o=4, p=1, r=1, s=2, t=1, u=2, v=1, W=1, y=1}

We can see that the above code is case sensitive as it treats M and m as two different characters. We can remove this by converting the string into either lower case or upper case by using methods such as  toLowerCase() or toUpperCase().

Leave a comment

Your email address will not be published. Required fields are marked *