Count the occurrences of individual characters in a string
Import Java.util.iterator;import Java.util.set;import Java.util.treemap;public class Treemapdemo {// Counts the number of occurrences of the corresponding character in a string public static void main (string[] args) {//String s = "AAGFAGDLKERJGAVPOFJMVGLK I am Yours"; Call a custom method to count the number of occurrences of the corresponding character, method (s);} private static void Method (String s) {//define a container treemap<character,integer> TM = new Treemap<character,integer> ;();//Remove the key from the TreeMap and store it in the set set to Set<character> st = Tm.keyset ();//Convert the string you want to count to a character array char[] C = S.tochararray ();//The number of occurrences of each character is counted by the 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 the custom method to output statistics Printmapdemo (tm) on the console;} private static void Printmapdemo (Treemap<character, integer> TM) {//TODO auto-generated method stubset< Character> st = Tm.keyset ();iterator<character> ti = St.iterator (); for (; Ti.hasnext ();) {char key = Ti.next (); System.out.println (key+ "(" +tm.get (key) + ")"}}} <span style= "font-family:fangsong_gb2312;" ></span>
To run the program:
Dark Horse Programmer--count the occurrences of each character in a string