Java Examples

java program to remove duplicate characters in a string

RemoveDuplicateFromString.java

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * @author Candid Java
 */

public class RemoveDuplicateFromString {
 public static void main(String[] args) throws Exception {
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  System.out.println("Enter the text :");
  String inpStr = br.readLine();
  StringBuilder sb = new StringBuilder();
  int n = inpStr.length();

  for (int i = 0; i < n; i++) {
   if (sb.toString().indexOf(inpStr.charAt(i)) == -1) {
    sb.append(String.valueOf(inpStr.charAt(i)));
   }
  }

  System.out.println("Actual string is: " + inpStr);
  System.out.println("String after removing duplicates: " + sb);

  br.close();
 }

}

Output

Enter the text :aaabbbcccababd
Actual string is: aaabbbcccababd
String after removing duplicates: abcd