In some projects, you may need to count words in a string. I have written a simple demo here. Students who need it can take a look.
If you don't talk nonsense, just post the code:
Implementation code:
/** * Statistics the number of occurrences of each word* @param text */ public static void findEnglishNum(String text){ //Find out all words String[] array = {".", " ", "?", "?", "!"}; for (int i = 0; i < array.length; i++) { text = text.replace(array[i],","); } String[] textArray = text.split(","); //Travel the record Map<String, Integer> map = new HashMap<String, Integer>(); for (int i = 0; i < textArray.length; i++) { String key = textArray[i]; //Convert to lowercase 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); } } } //Output to console System.out.println("The frequency of each word appears is: "); 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-------------------"); } }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 expert. 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); }Running results:
There are still some behind that have not been cut off
The above is all the content of this article. I hope that the content of this article will be of some help to everyone’s study or work. I also hope to support Wulin.com more!