隐藏行号复制代码这是一段程序代码。
  1. /**
  2.  * Java 统计一个字符串中的相同单词个数
  3.  */
  4. import java.util.HashMap;
    
  5. import java.util.Iterator;
    
  6. import java.util.Map;
    
  7. import java.util.Map.Entry;
    
  8. import java.util.Set;
    
  9. public class CountWords {
    
  10. private static String sentence = "Beijing on Friday urged Washington to respect historical facts and "
  11. + "not take sides on territorial disputes in the East China Sea and South China Sea, as US Secretary "
  12. + "of State John Kerry met Chinese leaders.";
    
  13. public static void countWord(String str){
    
  14. //将字符串按照规则截取为String数组
  15. String[] strToArray = str.split("[' '|,|.]");
    
  16. //建立Map,存储获得的单词为Key值,出现次数为对应的Value值
  17. Map<String, Integer> strMap = new HashMap<String, Integer>();
    
  18. //遍历数组
  19. for(int i=0;i<strToArray.length;i++){
    
  20. if(" "!=strToArray[i]){
    
  21. if(strMap.containsKey(strToArray[i])){
    
  22.                     strMap.put(strToArray[i], strMap.get(strToArray[i])+1);
    
  23.                 }else
  24. strMap.put(strToArray[i], 1);
    
  25.             }
    
  26.         }
    
  27.         Set<Entry<String, Integer>> it = strMap.entrySet();
    
  28.         Iterator<Entry<String, Integer>> iter = it.iterator();
    
  29. while(iter.hasNext()){
    
  30.             Entry<String, Integer> end = (Entry<String, Integer>) iter.next();
    
  31.             System.out.println("单词"+end.getKey()+"出现的次数:"+end.getValue());
    
  32.         }
    
  33.     }
    
  34. public static void main(String[] args) {
    
  35.         countWord(sentence);
    
  36.     }
    
  37. }