Write a program to count the frequency of each character in a string.
Example:
Input: "beingcodeexpert"
Output: beingcodeexpert : {p=1, b=1, r=1, c=1, d=1, t=1, e=4, g=1, x=1, i=1, n=1, o=1}
Approach
Java
import java.util.HashMap;public class Main {public static void main(String[] args) {frequencyCount("beingcodeexpert");}private static void frequencyCount(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);}}
No comments:
Post a Comment