How to find Duplicate characters in given String in Java?
Problem Description :
Write a program in Java that prints all duplicate characters in a String. For example "Java" has one duplicate character 'a'.
Algorithm :
- Convert original String to character Array.
- Remove all duplicate characters from String by converting String to Set.
- Get new String by converting Set (from Step 2) to String.
- Convert String (from Step 3) to character Array.
- If original String and new String are same then there is no duplicate character in original String otherwise go to Step 6.
- One by one check all characters of new String with Original String. If count > 1 it means duplicate characters present in String.
Java Program :
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.javamultiplex.string; | |
import java.util.HashSet; | |
import java.util.Iterator; | |
import java.util.LinkedHashSet; | |
import java.util.Scanner; | |
/** | |
* | |
* @author Rohit Agarwal | |
* @category String Interview Question | |
* @Problem Print all duplicate characters in a String | |
* | |
*/ | |
public class DuplicateCharactersInString { | |
public static void main(String[] args) { | |
Scanner input = null; | |
try { | |
input = new Scanner(System.in); | |
System.out.println("Enter String: "); | |
String string = input.next(); | |
// Converting String to char array. | |
char[] stringToChar = string.toCharArray(); | |
int orignalLength = stringToChar.length, charCount = 0; | |
String newString = getStringAfterDuplicatesRemoval(stringToChar); | |
// Converting String to char array. | |
char[] stringToCharAfterDuplicateRemoval = newString.toCharArray(); | |
int newLength = stringToCharAfterDuplicateRemoval.length; | |
if (string.equals(newString)) { | |
System.out.println("No duplicate character available."); | |
} else { | |
System.out.println("Duplicate characters are: "); | |
for (int i = 0; i < newLength; i++) { | |
charCount = 0; | |
for (int j = 0; j < orignalLength; j++) { | |
if (stringToCharAfterDuplicateRemoval[i] == stringToChar[j]) { | |
charCount++; | |
} | |
} | |
if (charCount > 1) { | |
System.out.println(stringToCharAfterDuplicateRemoval[i]); | |
} | |
} | |
} | |
} finally { | |
if (input != null) { | |
input.close(); | |
} | |
} | |
} | |
// Removing duplicates by converting char Array to Set. | |
private static String getStringAfterDuplicatesRemoval(char[] stringToChar) { | |
HashSet<Character> set = new LinkedHashSet<>(); | |
String result = ""; | |
int orignalLength = stringToChar.length; | |
for (int i = 0; i < orignalLength; i++) { | |
set.add(stringToChar[i]); | |
} | |
Iterator<Character> iterator = set.iterator(); | |
while (iterator.hasNext()) { | |
result += iterator.next(); // Converting Set to String | |
} | |
return result; | |
} | |
} |
Output :
Case 1 :
![]() |
Output - Duplicate characters present in given String. |
Case 2 :
![]() |
Output - Duplicate characters not present in given String. |
References :
https://www.tutorialspoint.com/java/java_hashset_class.htm
https://www.tutorialspoint.com/java/java_linkedhashset_class.htm
https://www.tutorialspoint.com/java/java_strings.htm
https://www.tutorialspoint.com/java/java_using_iterator.htm
Thank you friends, I hope you have clearly understood the solution of this problem. If you have any doubt, suggestion or query please feel free to comment below. You can also discuss this solution in our forum.
Tags : Interview questions on String, Solution in Java, Duplicate characters, Iterator, HashSet, LinkedHashSet, for loop, while loop, if statement, char[] array, String functions.
How to find Duplicate characters in given String in Java?
Reviewed by Rohit Agarwal
on
10/23/2016
Rating:

Hello Rohit,
ReplyDeleteCan't we solve this problem in little simpler and short way.
Because we have to just count the number of characters that are repeated.
Can't we do it just using HashMap().
If we then the solution will become very small and easy to understand.
May be I am wrong. Please update me on this
Hi Piyush,
DeleteWe have to print duplicate characters in String. Yes, we can do this problem using HashMap() but I don't think so that is short and simple because we have to perform following steps.
1) Break string into characters.
2) Found the count corresponding to each character -> To achieve this we need nested loop.
3) Take character as a Key and character count as a value, then store it into HashMap().
4) In HashMap() check for which Key , Value is greater than 1 and finally print Keys.
If you have any better approach to solve this problem using HashMap() please share with us. I will be more happy to see your approach :)
Hello Rohit
DeleteI think we can solve this problem using following steps,
HashMap map,
Count=0,
for i=0, i<length(string), i++
{
Chari=string.charat(i),
If(map.haskey(chari))
Count++
Else
Map.add(chari,0),
}
I don't know the exact function name but I think we can do it in this manner.
DeletePlease response..
Thank you.
Nice article String Programs in Java
ReplyDeletethanks.
Thank you Anurag.
DeleteRohit bhai appke hashset article mere interview clear me kaam aaya. Sir ji aapka bahut thanks.
ReplyDeleteCheers,
http://www.flowerbrackets.com/hashset-java/