Dark Horse Programmer--count the occurrences of each character in a string

Source: Internet
Author: User


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&gt ;();//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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.