This article describes the Java programming method to implement statistics on the occurrence of each character in a string. Share it for your reference, as follows:
import java.util.Iterator;import java.util.Set;import java.util.TreeMap;public class TreeMapDemo{//Search the number of times corresponding characters appear in a string public static void main(String[] args) { //System.out.println("Wulin.com test result:"); String s = "aagfagdlkerjgavpofjmvglk I am yours"; //Call custom methods to count the number of times corresponding characters appearing method(s); } private static void method(String s) { //Define a container TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>(); //Take all the keys in this TreeMap, and store them in the set set to Set<Character> st = tm.keySet(); //Convert the string you need to count into a character array char[] c = s.toCharArray(); //Calculate the number of times each character appears one by one through a for loop for(int x=0;x<c.length;x++) { if(!st.contains(c[x])) { tm.put(c[x], 1); } else { tm.put(c[x], tm.get(c[x])+1); } } //Call custom methods to output statistics on the console printMapDemo(tm); } private static void printMapDemo(TreeMap<Character, Integer> tm) { // TODO Auto-generated method stub Set<Character> st = tm.keySet(); Iterator<Character> ti = st.iterator(); for(;ti.hasNext();) { char key = ti.next(); System.out.println(key+"("+tm.get(key)+")"); } }}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.