#JavaInspires
Hi Guys,
Welcome to Java Inspires.😀
In this post, we will see how to get each character count from a string.
Here, we will take a string and convert to char array. Then we iterate over char array and put each character count in map. Here is the code.
JavaBasicExample.java
package com.javainspires; import java.util.HashMap; import java.util.Map; /** * * @author Java Inspires * */ public class JavaBasicExample { public static void main(String[] args) { // take a string String testStr = "AADDDFFGGGGGGGUUFZZZZZZZZZZZZZZ"; // convert string to char array char[] chararr = testStr.toCharArray(); // take a map to store char count Map<Character, Integer> charCount = new HashMap<Character, Integer>(); // iterate over char array for (char c : chararr) { // check for char in map if (charCount.containsKey(c)) { // if avaialble // get count and increment by 1 int count = charCount.get(c); charCount.put(c, count + 1); } else { // put char in map with count 1 charCount.put(c, 1); } } // print count map System.out.println(charCount); } }
Output:
{A=2, D=3, U=2, F=3, G=7, Z=14}