3

The string userKeyword comes from user keyboard input - I have tried to write a method to return this string with duplicate characters removed.

It is suggested that I use charAt and indexOf to complete this task, so the simplest way appeared to be to run through an alphabet letting indexOf pick out any characters that appear in the keyword and concatenate them together. I have tried to do this below but have not been successful.

Is there a simpler or more direct way of accomplishing this?

Why does my code not work? (I get a return of 26 'a's)

public static final String PLAIN_ALPHA = "abcdefghijklmnopqrstuvwxyz";

private String removeDuplicates(String userKeyword){

    int charLength = PLAIN_ALPHA.length();
    int charCount = 0;
    char newCharacter = PLAIN_ALPHA.charAt(charCount);
    String modifiedKeyword = "";

    while (charCount < charLength){

            if (userKeyword.indexOf(newCharacter) != -1);{
            modifiedKeyword = modifiedKeyword + newCharacter;
            }

            charCount = charCount + 1;
    }

    return modifiedKeyword;
}

    while (charCount < charLength){

            newCharacter = PLAIN_ALPHA.charAt(charCount);

            if (userKeyword.indexOf(newCharacter) != -1);{
            modifiedKeyword = modifiedKeyword + newCharacter;
            }

            charCount = charCount + 1;

With the newCharacter assignment shifted inside the while loop, I now get an output that is just the same as PLAIN_ALPHA instead of userKeyword with duplicates omitted. What am I doing wrong?

2 Answers2

5

You can do it in just one line:

private String removeDuplicates(String userKeyword){
    return userKeyword.replaceAll("(.)(?=.*\\1)", "");
}

This works by replacing with blank (ie removing) all characters that appear again later in the string, achieved by using a "look ahead" for a back-reference to the captured character.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
3

you can try this ...

private String removeDuplicates(String userKeyword){

        int charLength = userKeyword.length();
        String modifiedKeyword="";
        for(int i=0;i<charLength;i++)
            {
             if(!modifiedKeyword.contains(userKeyword.charAt(i)+""))
                 modifiedKeyword+=userKeyword.charAt(i);
            }
        return modifiedKeyword;
    }
HybrisHelp
  • 5,518
  • 2
  • 27
  • 65