. 【JAVA】給定任意 字串"yekmaakkccekymbvb",求出字串中有多少種字元,以及每個字元的個數?

sunnylovecmc發表於2009-11-30

import java.util.HashMap;
import java.util.Set;
public class SS {
 public static void main(String[] args) {
 
  HashMap<Character, Integer> s = SS.S("yekmaakkccekymbvb");
  Set<Character> hashSet=s.keySet();
  for (Character character : hashSet) {
   System.out.println("字母"+character+":共"+s.get(character)+"個");
  }
 }
 private static HashMap<Character, Integer> S(String string) {
  HashMap<Character, Integer> hashMap=new HashMap<Character, Integer>();
  char[] cs=string.toCharArray();
  for (char c : cs) {
   if (hashMap.containsKey(c)) {
    Integer tem = hashMap.get(c);
    tem=tem+1;
    hashMap.put(c, tem);
   } else {
    hashMap.put(c, 1);
   }
  }
  return hashMap;
 }
}

相關文章