从字符串中删除重复字符的方法(Java)

从字符串中删除重复字符的方法(Java),java,loops,duplicates,Java,Loops,Duplicates,字符串userKeyword来自用户键盘输入-我尝试编写一个方法来返回此字符串,并删除重复字符 有人建议我使用charAt和indexOf来完成这项任务,因此最简单的方法似乎是通过字母表让indexOf挑选出现在关键字中的任何字符并将它们连接在一起。我在下面尝试过,但没有成功 有没有更简单或更直接的方法来实现这一点 为什么我的代码不起作用?(我得到26'a的回报) public static final String PLAIN_ALPHA=“abcdefghijklmnopqrstuvxyz”

字符串userKeyword来自用户键盘输入-我尝试编写一个方法来返回此字符串,并删除重复字符

有人建议我使用charAt和indexOf来完成这项任务,因此最简单的方法似乎是通过字母表让indexOf挑选出现在关键字中的任何字符并将它们连接在一起。我在下面尝试过,但没有成功

有没有更简单或更直接的方法来实现这一点

为什么我的代码不起作用?(我得到26'a的回报)

public static final String PLAIN_ALPHA=“abcdefghijklmnopqrstuvxyz”;
私有字符串RemovedUpplicates(字符串userKeyword){
int charLength=PLAIN_ALPHA.length();
int charCount=0;
char newCharacter=PLAIN_ALPHA.charAt(字符数);
字符串modifiedKeyword=“”;
while(字符数<字符长度){
if(userKeyword.indexOf(newCharacter)!=-1){
modifiedKeyword=modifiedKeyword+新字符;
}
charCount=charCount+1;
}
返回修改后的关键字;
}

while(charCount
随着newCharacter赋值在while循环中移位,我现在得到的输出与PLAIN_ALPHA相同,而不是userKeyword,省略了重复项。我做错了什么?

您可以试试这个

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;
    }
private String removeDuplicates(String userKeyword){
int charLength=userKeyword.length();
字符串modifiedKeyword=“”;

对于(int i=0;i您可以在一行中完成:

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

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

如果使用调试器,第一次可能只会看到查找
charAt
一次。您需要查看每个字符。查看@您可以这样做,而不必像使用
普通\u ALPHA
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;
    }
private String removeDuplicates(String userKeyword){
    return userKeyword.replaceAll("(.)(?=.*\\1)", "");
}