原文: https://beginnersbook.com/2014/07/java-program-to-find-duplicate-characters-in-a-string/

    该程序将找出String中的重复字符并显示它们的计数。

    1. import java.util.HashMap;
    2. import java.util.Map;
    3. import java.util.Set;
    4. public class Details {
    5. public void countDupChars(String str){
    6. //Create a HashMap
    7. Map<Character, Integer> map = new HashMap<Character, Integer>();
    8. //Convert the String to char array
    9. char[] chars = str.toCharArray();
    10. /* logic: char are inserted as keys and their count
    11. * as values. If map contains the char already then
    12. * increase the value by 1
    13. */
    14. for(Character ch:chars){
    15. if(map.containsKey(ch)){
    16. map.put(ch, map.get(ch)+1);
    17. } else {
    18. map.put(ch, 1);
    19. }
    20. }
    21. //Obtaining set of keys
    22. Set<Character> keys = map.keySet();
    23. /* Display count of chars if it is
    24. * greater than 1\. All duplicate chars would be
    25. * having value greater than 1.
    26. */
    27. for(Character ch:keys){
    28. if(map.get(ch) > 1){
    29. System.out.println("Char "+ch+" "+map.get(ch));
    30. }
    31. }
    32. }
    33. public static void main(String a[]){
    34. Details obj = new Details();
    35. System.out.println("String: BeginnersBook.com");
    36. System.out.println("-------------------------");
    37. obj.countDupChars("BeginnersBook.com");
    38. System.out.println("\nString: ChaitanyaSingh");
    39. System.out.println("-------------------------");
    40. obj.countDupChars("ChaitanyaSingh");
    41. System.out.println("\nString: #@[email protected]!#$%!!%@");
    42. System.out.println("-------------------------");
    43. obj.countDupChars("#@[email protected]!#$%!!%@");
    44. }
    45. }

    输出:

    1. String: BeginnersBook.com
    2. -------------------------
    3. Char e 2
    4. Char B 2
    5. Char n 2
    6. Char o 3
    7. String: ChaitanyaSingh
    8. -------------------------
    9. Char a 3
    10. Char n 2
    11. Char h 2
    12. Char i 2
    13. String: #@[email protected]!#$%!!%@
    14. -------------------------
    15. Char # 2
    16. Char ! 3
    17. Char @ 3
    18. Char $ 2
    19. Char % 2

    参考:

    HashMap