Java: Print a unique character in a string

前端 未结 17 1426
长情又很酷
长情又很酷 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:45

    Based on your desired output, you have to replace a character that initially has been already added when it has a duplicated later, so:

    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 + " ");
    
    }
    

提交回复
热议问题