JavaNo Comments

default thumbnail

How to remove duplicate or repeated characters from String in Java. There are 3 ways to remove duplicate characters from String in using Java;  

First method is to sort the character array of string and then remove duplicate characters in linear time. Second method is to use an auxiliary data structure like Set to keep track of characters already seen and then recreate String from Set.

The third method would be the brute force way of taking one string at a time and then removing all other occurrences of that string, rearranging the array, and then starting with the next element.

Remove duplicate Character in String

import java.util.Scanner;
class ab
{
public static void main(String arg[])
{
String word=new String();
System.out.println(“Enter word”);

Scanner sc=new Scanner(System.in);
String in=sc.nextLine();
for(int i=0;i<in.length();i++)
{
for(int j=0;j<word.length();j++)
{
if(in.charAt(i)!=word.charAt(j))
{
word=word+in.charAt(i);
}
}
}
System.out.println(word);
} }

Be the first to post a comment.

Add a comment