Tuesday, 16 February 2016

Write a java program to Remove duplicate characters in a given String ?

Write a java program to Remove duplicate characters in a given String ?

import java.util.LinkedHashSet;
import java.util.Scanner;
import java.util.Set;

public class RemoveDuplicateCharacters {
      public String removeDuplicates(String input) {
            Set<Character> set = new LinkedHashSet<>();
            for (int i = 0; i < input.length(); i++) {
                  set.add(input.charAt(i));
            }
            StringBuilder sb = new StringBuilder();
            for (Character c : set) {
                  sb.append(c);
            }
            return sb.toString();
      }
      public static void main(String[] args) {
            RemoveDuplicateCharacters rd = new RemoveDuplicateCharacters();
            Scanner scanner = new Scanner(System.in);
            System.out.println("Please enter a String:");
            String input = scanner.next();
            System.out.println("RESULT IS : "+rd.removeDuplicates(input));
      }
}

Ouput:
Please enter a String:
mmmaaadddhhhuuu

RESULT IS : madhu 

No comments:

Post a Comment