Java map Exercise-Get the number of occurrences of letters in a string (TreeMap implementation)

Source: Internet
Author: User
Tags chr

/* Exercise: "Kbashbdjsgfwhofihbfkwejhfiubjzfhaads" gets the number of occurrences of the letter in the string. Want to print results: A (3) B (4) d (2) ... The results show that each letter has a corresponding number of times. , indicating that there is a mapping between the characters and the number of times. Note: When a mapping relationship is found, you can select the Map collection. Because the map collection stores the mapping relationship. Why use a map collection? When there is a mapping between the data, you think of the map collection. Idea: 1, use the Charat () method of the string class to iterate through each character in a string. 2, define a map, because the output is ordered, so use the TreeMap collection. 3, iterate through each character in the string, determine if there is a key in the map,   if present, the key value +1,   if not present, the character as a key to map, and give the key value of 1.*/import Java.util.*;class MapTest3 { public static void Main (string[] args) {String str= "kbashbdjsgfwhofihbfkwejhfiubjzfhaads"; TreeMap tm=new TreeMap (); for (int i=0;i<str.length (); i++) {char ch=str.charat (i); Tm.containskey (CH))) Tm.put (ch,1); else{int t= (int) (Tm.get (CH)) +1;tm.put (ch,t);}} Set S=tm.keyset (); Iterator it=s.iterator (); while (It.hasnext ()) {char chr= (char) it.next (); int num= (int) tm.get (CHR); SOP (chr+ "..." +num);}} public static void Sop (Object obj) {System.out.println (obj);}}

Java map Exercise-Get the number of occurrences of letters in a string (TreeMap implementation)

Related Article

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.