import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
public class CountAppears {
public static void main(String[] args) {
String tmp = "";// 字符串
ArrayList<Map.Entry<String, Integer>> ls = new ArrayList<Map.Entry<String, Integer>>(
count(tmp, new HashMap<String, Integer>()).entrySet());
Collections.sort(ls, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> obj1,
Map.Entry<String, Integer> obj2) {
return (obj2.getValue() - obj1.getValue());
}
});
for (Map.Entry<String, Integer> e : ls) {
System.out.println(e.getKey() + "出現次數" + e.getValue());
}
}
public static Map<String, Integer> count(String str, Map<String, Integer> rs) {
if (str == null || str.equals(""))
return rs;
int isize = str.length();
String tempStr = str.substring(0, 1);
str = str.replaceAll(tempStr, "");
int tempStrSize = str.length();
rs.put(tempStr, isize - tempStrSize);
return count(str, rs);
}
}
Java計算字符在字符串內出現的次數
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.