如何在java中查找String中的重复字符?
Java程序在字符串中查找重复字符
package org.arpit.java2blog; import java.util.HashMap; import java.util.Set; public class StringFindDuplicatesMain { public static void main(String[] args) { String str = "java2blog.com "; HashMap charCountMap = new HashMap(); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (charCountMap.containsKey(c)) { charCountMap.put(c, charCountMap.get(c) + 1); } else { charCountMap.put(c, 1); } } for (Character c : charCountMap.keySet()) { if (charCountMap.get(c) > 1) System.out.println("duplicate character : " + c + " ====== " + " count : " + charCountMap.get(c)); } } }
当你运行上面的程序时,你会得到以下输出:
duplicate character : a ====== count : 2 duplicate character : o ====== count : 2