Tuesday, December 2, 2014

Count the number of chars in string..

public class Countnumber {
  public static void main(String args[]){
    String s = "aabbbccccdddddeeeeeeffffffffff";
    Map<Character, Integer> m =new HashMap<Character, Integer>();
    char c;
   
    int count = 1;
    for(int i= 0;i<s.length();i++){
     
      c = s.charAt(i);
      if(m.containsKey(c)){
        count = (int) m.get(c);
        count++;
      }else{
        count = 1;
      }
      m.put(c, count);
    }
    Iterator it = m.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pairs = (Map.Entry)it.next();
        System.out.println(pairs.getKey() + " = " + pairs.getValue());
    }
    for(Map.Entry<Character, Integer> entry : m.entrySet()){
      System.out.println(entry.getKey() + " = " + entry.getValue());
    }
  }
}
O/p  ::
f = 10
d = 5
e = 6
b = 3
c = 4
a = 2

No comments:

Post a Comment