Count the number of each character in a string appears

Exercise:

  • Count the number of each character in a string appears

Analysis:
1. Scanner obtain user input string
2. Create Map set, key is a string of characters, value is the number of characters
3. Traversal string, each character acquired
4. using the acquired character, Map collection to determine whether there is key

  • key exists:
By character (key), to obtain value (the number of characters) 
value ++ 
PUT (Key, value) to the new value stored in the Map collection

 

  • Key does not exist:
put(key,1)

 


5. Map traversal set, the output

    class public CaiNiao { 
        public static void main (String [] args) { 
            . //. 1 using Scanner obtain user input string 
            Scanner SC = new new Scanner (the System.in); 
            System.out.println ( "Please enter a string : " );  string STR = sc.next ();  // Create Map 2 set, key is a string of characters, value is the number of characters.  the HashMap <Character.Integer> = new new Map the HashMap <> (); // 3 traversal string, each character acquired for (char C: str.toCharArray ()). {//. 4 characters using the acquired, determines whether the key set to Map exists iF (map.containsKey (C)) {// key = value exists Integer as map.get (C); ++ value ; map.put (C, value);} the else {// key not map.put (c, 1 present );}} // 5 traversal. Map collection output for(Character key : map.keySet(){ Integer value = map.get(key); System.out.println(key+"="+value); } } }

 

Guess you like

Origin www.cnblogs.com/cainiao-chuanqi/p/11223248.html