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计算字符在字符串内出现的次数
最新推荐文章于 2024-06-12 08:54:40 发布