Java:打印字符串中的唯一字符

新手上路,请多包涵

我正在编写一个程序,它将打印字符串中的唯一字符(通过扫描仪输入)。我已经创建了一个方法来尝试实现这一点,但我一直在获取不重复的字符,而不是字符串独有的一个或多个字符。我只想要独特的字母。

这是我的代码:

 import java.util.Scanner;
public class Sameness{
   public static void main (String[]args){
   Scanner kb = new Scanner (System.in);
     String word = "";

     System.out.println("Enter a word: ");
     word = kb.nextLine();

     uniqueCharacters(word);
}

    public static void uniqueCharacters(String test){
      String temp = "";
         for (int i = 0; i < test.length(); i++){
            if (temp.indexOf(test.charAt(i)) == - 1){
               temp = temp + test.charAt(i);
         }
      }

    System.out.println(temp + " ");

   }
}

这是上面代码的示例输出:

 Enter a word:
nreena
nrea

预期输出为: ra

原文由 Dextra 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 671
2 个回答

根据你想要的输出,你必须替换一个最初已经添加的字符,当它稍后被复制时,所以:

 public static void uniqueCharacters(String test){
    String temp = "";
    for (int i = 0; i < test.length(); i++){
        char current = test.charAt(i);
        if (temp.indexOf(current) < 0){
            temp = temp + current;
        } else {
            temp = temp.replace(String.valueOf(current), "");
        }
    }

    System.out.println(temp + " ");

}

原文由 lmiguelvargasf 发布,翻译遵循 CC BY-SA 3.0 许可协议

如何应用 KISS 原则:

 public static void uniqueCharacters(String test) {
    System.out.println(test.chars().distinct().mapToObj(c -> String.valueOf((char)c)).collect(Collectors.joining()));
}

原文由 Bohemian 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题