输入一串字符串,统计各个字符出现的次数
public class StatisticZEN { public static void main(String[] args) { String str = "中国aadf的111萨bbb菲的zz萨菲"; showFrequency(str); private static HashMap<Character, Integer> showFrequency(String str) { HashMap<Character, Integer> map = new HashMap<Character, Integer>(); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); Integer num = map.get(c); if(num == null) num = 1; else num ++; map.put(c,num); } return map; } }
统计文章中某个单词出现的频率
public class FrequencyOfWords { public static void main(String[] args) throws Exception { System.out.println(frequencyOfWords("student")); System.exit(0); } public static int frequencyOfWords(String string) throws Exception{ File file = new File("C:\\Users\\刘新成\\Desktop\\English.txt"); FileReader fr = new FileReader(file); char[] chars = new char[(int)file.length()]; fr.read(chars); String txt = String.valueOf(chars); String[] arr = txt.split("\\W+"); Map<String,Integer> map = new HashMap<String,Integer>(); for (String str : arr) { Integer frequency = map.get(str); if(frequency==null) frequency=1; else frequency++; map.put(str, frequency); } return map.get(string); } }