Occurrence of a character in a string using Java
Hi coders! You have been solving various String related problems some difficult some easy but this time I am here with a different type of problem which some of you people may have already seen or maybe not. Also for this problem, I have come up with an efficient solution using Java which you people will definitely be going to like. The task is to find the occurrence of a character in a string in Java. For example :
If the given string is: “code speedy”, then the output should be like-
Output : c = 1 o = 1 d = 2 e = 3 s = 1 p = 1 y = 1
Now to solve this problem there may be various methods which may seem easy to code but personally, I found the efficient approach for this problem which is Hashmap. Hashmap works on {key, value} pair.Using Hashmap one has to traverse the whole string once which reduces the time complexity and obviously, a good programmer always looks for a less complex solution. So following are steps to solve the given problem using Hashmap.
- First of all declare a Hashmap of {char,int}.
- Traverse the string and check for the traversed character in Hashmap.
- Count the frequency of each character.
- After traversing the string, traverse the Hashmap and print the character with its frequency of occurrence.
Program to find the occurrence of a character in a string in Java
Here in this code, we take a Hashmap named as charCount which is of {character, Integer}. In this code what we will do is that if the hashmap contains the character we will increment the count by 1 and will put the character in the Hashmap else if the character is not present in the hashmap we will put the character to Hashmap with 1 as it’s value. finally, after traversing the string once we will print the Hashmap by using the command “entry.getKey()” and ” entry.getValue()”.
Hence, using Hashmap the solution becomes efficient as well as easy.
import java.io.*; import java.util.*; class Occurence { // function for the character occurence frequency static void characterOccurence (String inpstr) { //creating a Hashmap of {char,int} Hashmap<Character,Integer> charCount = new Hashmap<>(); // converting string to character char[] strArr = inpStr.toCharArray(); for (char ch : strArr) { if (charCount.containsKey(ch)) { // If char is present in Hashmap then // incrementing it's count by 1 charCount.put(ch, charCount.get(ch) } else { // If char is not present in the Hashmap then // putting this char to Hashmap with 1 as it's value charCount.put(c, 1); } } // Printing the charCount for (Map.Entry entry : charCountMap.entrySet()) { System.out.println(entry.getKey() + " = " + entry.getValue()); } } //main function public static void main(str [] args) { String str = " Arjeet"; //calling function with str as argument characterOccurence(str); } }
Output:
A = 1 r = 1 j = 1 e = 2 t = 1
Hope the article is helpful to you.
You may also like to learn:
Leave a Reply