Home > Java > javaTutorial > Analysis of the method of counting the number of words in a string in java

Analysis of the method of counting the number of words in a string in java

高洛峰
Release: 2017-01-19 15:08:07
Original
1633 people have browsed it

In some projects, it may be necessary to count the words in a string. I have written a simple demo here. Students in need can take a look.

Don’t talk nonsense and just post the code:

Implementation code:

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


##Test code:

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);   }
Copy after login
Run results:

Analysis of the method of counting the number of words in a string in java

There are some things that have not been cut out

The above is the entire content of this article. I hope the content of this article will be useful to everyone. It can bring some help to your study or work, and I also hope that there will be more PHP Chinese websites!

For more java methods to count the number of words in a string and related articles, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template