- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java program to delete duplicate characters from a given String
The interface Set 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
- Convert it 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
Example
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 :: malayalam indices of the duplicate characters in the given string :: Index :: 3 character :: a Index :: 5 character :: a Index :: 6 character :: l Index :: 7 character :: a Index :: 8 character :: m
- Related Articles
- Program to remove duplicate characters from a given string in Python
- Java Program to find duplicate characters in a String?
- C Program to delete n characters in a given string
- C# Program to remove duplicate characters from String
- Java program to find all duplicate characters in a string
- Java Program to Find the Duplicate Characters in a String
- Python program to find all duplicate characters in a string
- JavaScript Remove non-duplicate characters from string
- Find All Duplicate Characters from a String using Python
- Python program to extract characters in given range from a string list
- Java program to delete duplicate lines in text file
- Java program to count upper and lower case characters in a given string
- Program to find string after removing consecutive duplicate characters in Python
- Java Program to Get a Character From the Given String
- Program to find string after deleting k consecutive duplicate characters in python

Advertisements