Java: Print a unique character in a string

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

    Step1: To find the unique characters in a string, I have first taken the string from user. Step2: Converted the input string to charArray using built in function in java. Step3: Considered two HashSet (set1 for storing all characters even if it is getting repeated, set2 for storing only unique characters. Step4 : Run for loop over the array and check that if particular character is not there in set1 then add it to both set1 and set2. if that particular character is already there in set1 then add it to set1 again but remove it from set2.( This else part is useful when particular character is getting repeated odd number of times). Step5 : Now set2 will have only unique characters. Hence, just print that set2.

    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        String str = input.next();
        char arr[] = str.toCharArray();
        
        HashSet set1=new HashSet();
        HashSet set2=new HashSet();
    
        
        for(char i:arr)
        {
            if(set1.contains(i))
            {
                set1.add(i);
                set2.remove(i);
                
            }
            else
            {
                
                set1.add(i);
                set2.add(i);
            }
        }
        
        System.out.println(set2); 
    
    }
    

提交回复
热议问题