This article describes the method of calculating the words with the most occurrences in English sentences and calculating the occurrences. Share it for your reference, as follows:
import java.util.*;/** * Count the word with the most occurrences and the number of occurrences* * @author ZHR */public class CountWord { public static String[] strTostrArray(String str) { /* * Replace all non-letter characters with space characters " " Get a pure alphabetical string containing space characters */ str = str.toLowerCase();// Change all characters in the English part of the string to lowercase String regex = "[//W]+";// Non-letter regular expression-/W: represents any non-word character str = str.replaceAll(regex, " "); String[] strs = str.split(" "); // Use spaces as delimiters to obtain the string array return strs; } public static void countword(String[] strs) { /* * Create a mapping of the number of occurrences of strings (String) (Integer)*/ HashMap<String, Integer> strhash = new HashMap<String, Integer>(); Integer in = null;// The return value used to store the put operation for (String s : strs) {// traverse the array strs in = strhash.put(s, 1); if (in != null) {// 1. Integer value = e.getValue(); if (value > maxValue) { maxValue = value;// There is automatic unboxing maxStr = key; } } System.out.println("The word that appears the most is: " + maxStr + "appeared" + maxValue + "times"); } @SuppressWarnings("resource") public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Please enter a line of English sentences: "); String str = scan.nextLine(); System.out.println("The English sentence entered is: " + str); String[] strs = strTostrArray(str); countword(strs); }}Running results:
PS: Here are two very convenient statistical tools for your reference:
Online word count tool:
http://tools.VeVB.COM/code/zishutongji
Online character statistics and editing tools:
http://tools.VeVB.COM/code/char_tongji
For more information about Java algorithms, readers who are interested in this site can view the topics: "Java Data Structure and Algorithm Tutorial", "Summary of Java Operation DOM Node Tips", "Summary of Java File and Directory Operation Tips" and "Summary of Java Cache Operation Tips"
I hope this article will be helpful to everyone's Java programming.