Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Print a unique character in a string

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 characters that are not repeats, instead of a character (or characters) that is unique to the string. I want the unique letters only.

Here's my code:

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

   }
}            

And here's sample output with the above code:

Enter a word: 
nreena
nrea 

The expected output would be: ra

like image 405
Dextra Avatar asked Nov 30 '16 23:11

Dextra


People also ask

How do I print unique characters in a string?

Given a string, find the all distinct (or non-repeating characters) in it. For example, if the input string is “Geeks for Geeks”, then output should be 'for' and if input string is “Geeks Quiz”, then output should be 'GksQuiz'. The distinct characters should be printed in same order as they appear in input string.

How do I return a unique character from a string in Java?

Using the toCharArray() method The toCharArray() method of the String class converts the given String into an array of characters and returns it. Convert it into an array of characters. Compare each character in the array with the required one. In case of a /match the String contains the required character.

How do I find a specific character in a string in Java?

To locate a character in a string, use the indexOf() method.


2 Answers

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

}
like image 198
lmiguelvargasf Avatar answered Oct 14 '22 09:10

lmiguelvargasf


How about applying the KISS principle:

public static void uniqueCharacters(String test) {
    System.out.println(test.chars().distinct().mapToObj(c -> String.valueOf((char)c)).collect(Collectors.joining()));
}
like image 21
Bohemian Avatar answered Oct 14 '22 09:10

Bohemian