Table of Contents
In this post, we will see how to find duplicate Characters in a String.
When you run above program, you will get below output:
Approach:
- Create a HashMap and character of String will be inserted as key and its count as value.
- If Hashamap already contains char,increase its count by 1, else put char in HashMap
- If value of Char is more than 1, that means it is duplicate character in that String
Java Program to find duplicate Characters in a String
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
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)); } } } |
1 2 3 4 |
duplicate character : a ====== count : 2 duplicate character : o ====== count : 2 |
Other String Programs :
- How to reverse String in java
- How to check if two Strings are angrams
- Find length of String without using java inbuilt length method
- Find all substrings of String in java
- Find First non repeated character in a String
- Java Program to check Palindrome String
- Why String is immutable in java
- Find duplicate characters in String
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.
How about using a Set?
private static boolean hasDupeLetter(String str) {
if(null == str || str.length() <= 1) { return false; } Set set = new HashSet ();
for(int i = 0; i < str.length(); i++) { set.add(str.charAt(i)); } return str.length() == set.size(); }