![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Advertisements