Java: Print a unique character in a string

前端 未结 17 1411
长情又很酷
长情又很酷 2021-01-03 00:03

I\'m writing a program that will print the unique character in a string (entered through a scanner). I\'ve created a method that tries to accomplish this but I keep getting

17条回答
  •  误落风尘
    2021-01-03 00:42

    Though to approach a solution I would suggest you to try and use a better data structure and not just string. Yet, you can simply modify your logic to delete already existing duplicates using an else as follows :

    public static void uniqueCharacters(String test) {
            String temp = "";
            for (int i = 0; i < test.length(); i++) {
                char ch = test.charAt(i);
                if (temp.indexOf(ch) == -1) {
                    temp = temp + ch;
                } else {
                    temp.replace(String.valueOf(ch),""); // added this to your existing code
                }
            }
    
            System.out.println(temp + " ");
    
        }
    

提交回复
热议问题