【问题标题】:Method for removing duplicate chars from a string (Java)从字符串中删除重复字符的方法(Java)
【发布时间】:2013-08-12 04:57:38
【问题描述】:

字符串 userKeyword 来自用户键盘输入 - 我试图编写一个方法来返回删除重复字符的字符串。

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

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

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

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;

在 while 循环内转移 newCharacter 赋值后,我现在得到一个与 PLAIN_ALPHA 相同的输出,而不是 userKeyword 并省略了重复项。我做错了什么?

【问题讨论】:

  • 如果您使用调试器,您可能会看到您只查找charAt 一次,这是第一次。您需要查看每个字符。
  • 您可以在不使用任何其他字符串的情况下执行此操作,因为您使用PLAIN_ALPHA

标签: java loops duplicates


【解决方案1】:

只需一行即可完成:

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

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

【讨论】:

    【解决方案2】:

    你可以试试这个...

    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;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-21
      • 2017-12-17
      • 1970-01-01
      • 2011-09-04
      • 2013-09-18
      • 1970-01-01
      • 1970-01-01
      • 2020-03-30
      相关资源
      最近更新 更多