Query the number of letters in a string (two implementation methods: 1. list and set 2. map set)
Question:
The number of times a letter appears in a string. For example: String: "abcde % ^ kka27qoq", output format: a (2) B (1) k (2 )...
The first method (used in combination with set and list ):
Package itheima; import java. util. arrayList; import java. util. linkedHashSet; import java. util. list; import java. util. set ;/***. the number of times a letter appears in a string. For example: String: "abcde % ^ kka27qoq", output format: a (2) B (1) k (2 )... * @ author Administrator **/public class Demo6 {public static void main (String [] args) {String str = "abcdekka27qoA * & AAAq "; // The countStringNumber (str) function for querying the number of letters in a String;} private static void countStringNumber (String str) {// convert a String to a character array char [] array = str. toCharArray (); // use set in combination. The sorted hashset has an order and does not repeat the Set
Set = new LinkedHashSet
(); // Add the characters (not repeated) in the array to the set for (int I = 0; I <array. length; I ++) {set. add (array [I]);} // converts a set to a list set.
List = new ArrayList
(Set); for (int I = 0; I <list. size (); I ++) {int count = 0; // variable that records the number of characters for (int j = 0; j <array. length; j ++) {if (list. get (I ). equals (array [j]) {// you can determine that the letters in the list that have been paid are the same as the letters in the array. count is added to 1 count ++;} System. out. print (list. get (I) + "(" + count + ")"); // output }}}
Method 2 (map set ):
Package itheima; import java. util. iterator; import java. util. linkedHashMap; import java. util. map; import java. util. map. entry; public class Demo7 {public static void main (String [] args) {String str = "abcdekka27qoA * & AAAq "; // function for querying the number of letters in a String countStringNumber (str);} private static void countStringNumber (String str) {// convert it to a character array char [] c = str. toCharArray (); // System. out. println (c); // use the map set to explain the hashmap ordered Map
Map = new LinkedHashMap
(); // Traverse for (int I = 0; I <c. length; I ++) {// if the key in the set does not contain c [I], it is set to 1if (! Map. keySet (). contains (c [I]) {map. put (c [I], 1);} else {// No, 1map is added. put (c [I], map. get (c [I]) + 1) ;}// iteration set Iterator
> It = map. entrySet (). iterator (); while (it. hasNext () {Entry
Entry = it. next (); System. out. print (entry. getKey () + "(" + entry. getValue () + ")");}}}
Running result: