import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; public class StringSum { /** * 统计一段英文中出现次数最多的单词 * @param filePath 文件的路径 * @throws Exception */ public static void stringSumMethod(String filePath) throws Exception{ File file=new File(filePath); FileInputStream input=new FileInputStream(file); BufferedReader bf=new BufferedReader(new InputStreamReader(input)); StringBuffer sb=new StringBuffer(); String content=""; while((content=bf.readLine())!=null){ sb.append(content); } bf.close(); input.close(); //System.out.println(sb.toString()); String[] contents=sb.toString().split(" "); //System.out.println(contents.length); Map<String,Integer> map=new HashMap<String, Integer>(); for(int i=0;i<contents.length;i++){ //System.out.println(contents[i]); if(contents[i].equals("0")) continue; int times=1; for(int j=0;j<contents.length;j++){ if(contents[j].equals("0")) continue; if(i==j) continue; if(contents[i].equals(contents[j])){ times++; contents[j]="0";//出现重复的就将重复的字符置"0" } //System.out.println(contents[i]+":"+times+"当前次数:"+j); } //System.out.println(contents[i]+":"+times+"当前次数:"+i); map.put(contents[i],times); } // System.out.println(map.size()); //System.out.println(map.toString()); int maxValue=0; String maxKey=""; for (Map.Entry<String, Integer> entry : map.entrySet()) { // System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue()); if(entry.getValue()>maxValue){ maxValue=entry.getValue(); maxKey=entry.getKey(); } } System.out.println("出现最多的字符串:"+maxKey+" 出现次数:"+maxValue); } }