Write a java program to remove Duplicate Characters in String

Write a Program which removes duplicate characters from the string. Your program should read a sentence (string) as input from user and return a string removing duplicate characters. Retain the first occurance of the duplicate character. Assume the characters are case – sensitive.

 Input and Output Format:

Input consists of a string with maximum size of 100 characters.

Output consists of a single string.

Refer sample output for formatting specifications.

Sample Input 1:

hi this is sample test

Sample Output 1:

hi tsample

Sample Input 2:

ABC DEF

Sample Output 2:

ABC DEF

Java program to remove Duplicate Characters in String.

package testCases;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Scanner;
public class MainJava {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s1 = sc.nextLine();
getvalues(s1);
}
public static void getvalues(String s1) {
char a[] = s1.toCharArray();
StringBuffer sb = new StringBuffer();
LinkedHashSet<Character> hs = new LinkedHashSet<Character>();
for (int i = 0; i < a.length; i++) {
hs.add(a[i]);
}
Iterator<Character> itr = hs.iterator();
while (itr.hasNext()) {
char o = itr.next();
if (o != ' ')
;
{
sb.append(o);
}
}
System.out.println(sb);
}
}

 

Add a Comment

Your email address will not be published. Required fields are marked *

one × 1 =