求字符串中字符的种类及其个数

//字符串"yekmaakkccekymbvb",求出字符串中有多少种字符,以及每个字符的个数

public class aaa {

  public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner scanner=new Scanner(System.in);
    System.out.println("请输入一个字符串:");
    String str=scanner.nextLine();

    Map<Character, Integer> count=getCountChar(str);
    System.out.println(count);
    System.out.println("---------------");

    System.out.println(getNumChar(str));

  }
  public static Map<Character, Integer> getCountChar(String str){
    Map<Character, Integer> map=new HashMap<Character, Integer>();
    for(int i=0;i<str.length();i++){
      Character c=str.charAt(i);
      Integer count=map.get(c);
      map.put(c, (count==null?1:count+1));
    }
    return map;
  }
  public static int getNumChar(String str){
    HashSet set=new HashSet();
    char[] ch=str.toCharArray();
    for(int i=0;i<ch.length;i++){
      set.add(ch[i]);
    }
    return set.size();
  }

}

 

posted @ 2015-08-01 11:29  飞牛冲天  阅读(716)  评论(0编辑  收藏  举报