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?

4

2 回答 2

5

您只需一行即可完成:

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

这通过用空白替换(即删除)字符串中稍后再次出现的所有字符来工作,通过使用“前瞻”来反向引用捕获的字符来实现。

于 2013-08-10T20:37:34.840 回答
3

你可以试试这个...

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;
    }
于 2013-08-10T09:55:24.573 回答