Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method for removing duplicate chars from a string (Java)

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?

like image 589
Joseph Diamond Avatar asked Feb 22 '26 21:02

Joseph Diamond


2 Answers

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.

like image 154
Bohemian Avatar answered Feb 24 '26 12:02

Bohemian


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;
    }
like image 38
HybrisHelp Avatar answered Feb 24 '26 10:02

HybrisHelp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!