Skip to main content

Count each character and sort the string

Here we have shown how to count the character occurrence in the string and print in sorted way




For example, you have a string :
input : bbcann
and your output would be 1b2c1n2 , means you have counted and also printed in sorted way from a to z.
This is commonly asked questions on online test.

public class App 
{
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
        System.out.print(countChracter("bbcann"));
    }
    
    
   static String countChracter(String s){
    char[] carray=s.toCharArray();
    Arrays.sort(carray);
    HashMap<Character,Integer> hm = new HashMap<Character, Integer>();
    for(char c : carray){
    if(hm.containsKey(c)){
    hm.put(c, hm.get(c)+1);
    }else{
    hm.put(c, 1);
    }
   
    }
    String output="";
    for(Map.Entry e: hm.entrySet()){
    output=output+e.getKey()+e.getValue();
    }
    return output;
    }
    
}



Comments