首頁  >  文章  >  Java  >  java統計字串單字個數的方法解析

java統計字串單字個數的方法解析

高洛峰
高洛峰原創
2017-01-19 15:08:071565瀏覽

在某些專案中可能需要對一段字串中的單字進行統計,我在這裡寫了一個簡單的demo,有需要的同學可以拿去看一下。

不說廢話了直接貼代碼:

實現代碼:

/**
   * 统计各个单词出现的次数
   * @param text
   */
  public static void findEnglishNum(String text){
   //找出所有的单词
   String[] array = {".", " ", "?", "!"};
   for (int i = 0; i < array.length; i++) {
    text = text.replace(array[i],",");
   }
   String[] textArray = text.split(",");
   //遍历 记录
   Map<String, Integer> map = new HashMap<String, Integer>();
   for (int i = 0; i < textArray.length; i++) {
    String key = textArray[i];
    //转为小写
    String key_l = key.toLowerCase();
    if(!"".equals(key_l)){
     Integer num = map.get(key_l);
     if(num == null || num == 0){
      map.put(key_l, 1);
     }else if(num > 0){
      map.put(key_l, num+1);
     }
    }
   }
   //输出到控制台
   System.out.println("各个单词出现的频率为:");
   Iterator<String> iter = map.keySet().iterator();
   while(iter.hasNext()){
    String key = iter.next();
    Integer num = map.get(key);
    System.out.println(key + "\n\t\t" + num + "次\n-------------------");
   }
  }

   


測試代碼:

public static void main(String[] args) {
   String text = "Welcome welcome to ADempiere, a commons-based peer-production of Open Source ERP Applications. This Wiki is for the global community to contribute and share know-how and domain expertise. We hope you can find as much open information and participate in making it most usable for everyone. This project has a bazaar of Citizens with a Community Council Team which work in theFunctional Team and Technical Team along the Software Development Procedure supported and funded by the foundation ADempiere";
   findEnglishNum(text);   }

運行的全部內容,希望本文的內容對大家的學習或工作能帶來一定的幫助,同時也希望多多PHP中文網!

更多java統計字串單字數的方法解析相關文章請關注PHP中文網! java統計字串單字個數的方法解析

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn