Find Character Count In a Given String

Here in this post we will find the count of each character in a given String. Lets Say for a given String “tuturself” the output should be the count of each word

r=1, s=1, t=2, u=2, e=1, f=1, l=1

Now let us check the code for this:

package com.tuturself.programs;

import java.util.HashMap;
import java.util.Map;

public class CharacterCountInString {
	
  public static void main(String [] args){
    String string = "tuturself";
    char [] charArray = string.toCharArray();
    Map<Character,Integer> characterCountMap = new HashMap<Character,Integer>();

    for(int i=0;i<charArray.length;i++){
      if(characterCountMap.containsKey(charArray[i])){
        characterCountMap.get(charArray[i]);
        characterCountMap.put(charArray[i], characterCountMap.get(charArray[i])+1);
      }
      else{
        characterCountMap.put(charArray[i], 1);
      }
    }
    System.out.println(characterCountMap.toString());
  } 
}

 

core java 12

FOLLOW US ON LinkedIn



Explore Tutu'rself