Search code examples
javastring

Removing duplicates from a String in Java


I am trying to iterate through a string in order to remove the duplicates characters.

For example the String aabbccdef should become abcdef and the String abcdabcd should become abcd

Here is what I have so far:

public class test {

    public static void main(String[] args) {

        String input = new String("abbc");
        String output = new String();

        for (int i = 0; i < input.length(); i++) {
            for (int j = 0; j < output.length(); j++) {
                if (input.charAt(i) != output.charAt(j)) {
                    output = output + input.charAt(i);
                }
            }
        }

        System.out.println(output);

    }

}

What is the best way to do this?


Solution

  • Convert the string to an array of char, and store it in a LinkedHashSet. That will preserve your ordering, and remove duplicates. Something like:

    String string = "aabbccdefatafaz";
    
    char[] chars = string.toCharArray();
    Set<Character> charSet = new LinkedHashSet<Character>();
    for (char c : chars) {
        charSet.add(c);
    }
    
    StringBuilder sb = new StringBuilder();
    for (Character character : charSet) {
        sb.append(character);
    }
    System.out.println(sb.toString());