>  기사  >  Java  >  Java에서 문자열의 단어 수를 계산하는 방법 분석

Java에서 문자열의 단어 수를 계산하는 방법 분석

高洛峰
高洛峰원래의
2017-01-19 15:08:071565검색

어떤 프로젝트에서는 문자열의 단어 수를 세어야 할 수도 있습니다. 여기에 간단한 데모를 작성했습니다.

쓸데없는 소리 하지 말고 코드만 게시하세요:

구현 코드:

/**
   * 统计各个单词出现的次数
   * @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);   }

실행 결과:

Java에서 문자열의 단어 수를 계산하는 방법 분석

아직 잘리지 않은 부분도 있습니다

위 내용은 전체 내용입니다 이 기사가 여러분의 공부나 업무에 도움이 되기를 바라며, PHP 중국어 웹사이트가 더 많아지기를 바랍니다.

문자열의 단어 수를 계산하는 더 많은 Java 방법 및 관련 기사를 보려면 PHP 중국어 웹사이트에 주목하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.