Delete Duplicate Characters from a Given String in Java



The Set interface does not allow duplicate elements, therefore, create a set object and try to add each element to it using the add() method in case of repetition of elements this method returns false ?

If you try to add all the elements of the array to a Set, it accepts only unique elements so, to find duplicate characters in a given string.

Problem Statement

Given a string, write a program in Java to delete duplicate characters from a given string ?

Input

TUTORIALSPOINT

Output

Indices of the duplicate characters in the given string :: 
Index :: 2 character :: T
Index :: 10 character :: O
Index :: 11 character :: I
Index :: 13 character :: T

Steps to delete duplicate characters from a given string

Following are the steps to delete duplicate characters from a given string ?

  • Import all the necessary classes.
  • Convert the string into a character array.
  • Try to insert elements of the above-created array into a hash set using add method.
  • If the addition is successful this method returns true.
  • Since Set doesn't allow duplicate elements this method returns 0 when you try to insert duplicate elements
  • Print those elements.

Java program to delete duplicate characters from a given string

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class DuplicateCharacters {
 public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the required string value ::");
String reqString = sc.next();
char[] myArray = reqString.toCharArray();
System.out.println("indices of the duplicate characters in the given string :: ");
Set set = new HashSet();

for(int i=0; i<myArray.length; i++){
 if(!set.add(myArray[i])){
System.out.println("Index :: "+i+" character :: "+myArray[i]);
 }
}
 }
}

Output

Enter the required string value ::
TUTORIALSPOINT
Indices of the duplicate characters in the given string :: 
Index :: 2 character :: T
Index :: 10 character :: O
Index :: 11 character :: I
Index :: 13 character :: T

Code Explanation

The program starts by importing necessary classes and interface:  HashSet, Scanner, and Set from java.util package. The main method initializes a Scanner to read the user's input string, which is then converted into a character array. A HashSet is used to store unique characters, leveraging its property of disallowing duplicates.

The program iterates through the character array with a for loop, using the add() method of HashSet to attempt adding each character. If a character is already present, add() returns false, and the program prints the index and the duplicate character. This method ensures that all duplicates are efficiently identified and output, utilizing HashSet for optimal performance in avoiding repeated elements. 

Updated on: 2024-07-31T17:49:38+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements