原文: https://beginnersbook.com/2014/07/java-program-to-find-duplicate-characters-in-a-string/
该程序将找出String中的重复字符并显示它们的计数。
import java.util.HashMap;import java.util.Map;import java.util.Set;public class Details {public void countDupChars(String str){//Create a HashMapMap<Character, Integer> map = new HashMap<Character, Integer>();//Convert the String to char arraychar[] chars = str.toCharArray();/* logic: char are inserted as keys and their count* as values. If map contains the char already then* increase the value by 1*/for(Character ch:chars){if(map.containsKey(ch)){map.put(ch, map.get(ch)+1);} else {map.put(ch, 1);}}//Obtaining set of keysSet<Character> keys = map.keySet();/* Display count of chars if it is* greater than 1\. All duplicate chars would be* having value greater than 1.*/for(Character ch:keys){if(map.get(ch) > 1){System.out.println("Char "+ch+" "+map.get(ch));}}}public static void main(String a[]){Details obj = new Details();System.out.println("String: BeginnersBook.com");System.out.println("-------------------------");obj.countDupChars("BeginnersBook.com");System.out.println("\nString: ChaitanyaSingh");System.out.println("-------------------------");obj.countDupChars("ChaitanyaSingh");System.out.println("\nString: #@[email protected]!#$%!!%@");System.out.println("-------------------------");obj.countDupChars("#@[email protected]!#$%!!%@");}}
输出:
String: BeginnersBook.com-------------------------Char e 2Char B 2Char n 2Char o 3String: ChaitanyaSingh-------------------------Char a 3Char n 2Char h 2Char i 2String: #@[email protected]!#$%!!%@-------------------------Char # 2Char ! 3Char @ 3Char $ 2Char % 2
参考:
