当前位置:网站首页>Case - count the number of occurrences of each string in the string

Case - count the number of occurrences of each string in the string

2022-06-13 05:05:00 Jason_ LH1024

 

package com.it.code01;

import java.util.HashMap;
import java.util.Scanner;
import java.util.Set;

public class HashMapDemo {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.println(" Please enter a string :");
        String line = sc.nextLine();

        // establish HashMap aggregate , The key is Character, The value is Integer
      //  HashMap<Character, Integer> hm = new HashMap<>();
        TreeMap<Character, Integer> hm = new TreeMap<>();

        // Traversal string , Get every character 
        for (int i = 0; i < line.length(); i++) {
            char key = line.charAt(i);

            // Take each string you get as a key to HashMap Find the corresponding value in the set , Look at the return value 
            Integer value = hm.get(key);

            if (value == null) {
                // If the return value is null, Indicates that the character is in HashMap There is no such thing as , Just 
                hm.put(key, 1);

            } else {
                // If the return value is null, Description the string is in the HashMap There is no such thing as ,
                // Just use this character as a key ,1 As a stored value 
                value++;
                hm.put(key, value);
            }
        }

        // Traverse HashMap aggregate , And we get the bond and the value , Splice as required 

        StringBuilder sb = new StringBuilder();

        Set<Character> keySet = hm.keySet();
        for (Character key : keySet) {
            Integer value = hm.get(key);
            sb.append(key).append("(").append(value).append(")");

        }
        String result = sb.toString();

        // Output results 
        System.out.println(result);
    }
}

原网站

版权声明
本文为[Jason_ LH1024]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280515587757.html