Program to remove duplicate character from string without loosing the order in which it inserted(The important one for Interview: String Continues….)

Posted by

I flunked once an interview because of this program.Interviewer asked me to write a program to remove duplicate character from string, but without loosing the order.I knew the Set interface which does not allow duplicates, but i could not memorize the class which maintains the order in which they were inserted.I tried alot but could not memorize.I was thrown out from the last round, lost the job. Here I am gonna post that program,I hope it will help you. 

Code: Remove duplicate character from string
import java.util.*;
class removeDuplicate
{
public String remove(String inputString)
{
String result = "";
Set<String> inputSet= new LinkedHashSet<String>(); //LinkedHashSet maintains the order in which elements are inserted
for(int i=0;i<inputString.length();i++)
{
inputSet.add(String.valueOf(inputString.charAt(i)));
}
for(String a: inputSet)
{
result += a;
}
return result;
}
public static void main(String java2carrer[])
{
removeDuplicate rd=new removeDuplicate();
System.out.println(rd.remove("abdacdabcd"));
}
}

Output :

Remove duplicate character from string

 

 

You may also like following string programs:

  1. Java program to find the first letter alphabetically in String
  2. A program to reverse a String (Without using API)
  3. A program to reverse a string and change first character case to lower case and last to lower case.
  4.  A program to check String is palindrom or not?

One comment

Leave a Reply