8

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

5
  • What is the expected output for 'nreena' ? Commented Nov 30, 2016 at 23:10
  • 1
    But e is a repeat, and you're still getting it. Is the desired output ra? Commented Nov 30, 2016 at 23:10
  • Anyways, I'd do something like char[] array = test.toCharArray(); and then loop through array for each letter in test and if there are no matches, do temp = temp + test.charAt(i);. Commented Nov 30, 2016 at 23:16
  • Yes, the desired output would be "ra". Commented Nov 30, 2016 at 23:16
  • Once you've added a character, you are not removing the existing one on finding its multiple occurrences. Commented Nov 30, 2016 at 23:29

20 Answers 20

10

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

}
Sign up to request clarification or add additional context in comments.

5 Comments

this is efficient!
Thank you so much!
Is there need of else block..?
@Suree, it is required. Basically, the else block is removing a character that at first was seen as unique, but once it has been found repeated should be removed.
@lmiguelvargasf, Actually else block removing every 2nd occurring char in temp. temp.indexOf(current) is checking as well character that at first was seen as unique in temp string. So, there is no need of else block. I have checked.
10

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()));
}

1 Comment

This is best answer with minimal execution time compared to above solutions.
3

The accepted answer will not pass all the test case for example

input -"aaabcdd"

desired output-"bc"
but the accepted answer will give -abc

because the character a present odd number of times.

Here I have used ConcurrentHasMap to store character and the number of occurrences of character then removed the character if the occurrences is more than one time.

import java.util.concurrent.ConcurrentHashMap;

public class RemoveConductive {

    public static void main(String[] args) {

        String s="aabcddkkbghff";

        String[] cvrtar=s.trim().split("");

        ConcurrentHashMap<String,Integer> hm=new ConcurrentHashMap<>();
        for(int i=0;i<cvrtar.length;i++){
            if(!hm.containsKey(cvrtar[i])){
                hm.put(cvrtar[i],1);
            }
            else{
                 hm.put(cvrtar[i],hm.get(cvrtar[i])+1);
            }
        }
        for(String ele:hm.keySet()){
            if(hm.get(ele)>1){
                hm.remove(ele);
            }
        }
        for(String key:hm.keySet()){
            System.out.print(key);
        }
    }  
}

Comments

2

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

    }

2 Comments

it seems funny, but my answer and yours look almost exactly the same, but just the name of a variable is changed. Though, I used this variable when it could be used, i.e., I do not repated test.charAt(i) more than once.
correct shouldn't have repeated its usage. was just trying to optimise OPs code. missed that.
1

This is an interview question. Find Out all the unique characters of a string. Here is the complete solution. The code itself is self explanatory.

public class Test12 {
    public static void main(String[] args) {
        String a = "ProtijayiGiniGina";

        allunique(a);
    }

    private static void allunique(String a) {
        int[] count = new int[256];// taking count of characters
        for (int i = 0; i < a.length(); i++) {
            char ch = a.charAt(i);
            count[ch]++;
        }

        for (int i = 0; i < a.length(); i++) {
            char chh = a.charAt(i);
            // character which has arrived only one time in the string will be printed out
            if (count[chh] == 1) {
                System.out.println("index => " + i + " and unique character => " + a.charAt(i));

            }
        }

    }// unique

}

In Python :

def firstUniqChar(a):
    count = [0] *256
    for i in a: count[ord(i)] += 1
    element = ""

    for item in a:
        if (count[ord(item)] == 1):
            element = item;
            break;
    return element        


a = "GiniGinaProtijayi";
print(firstUniqChar(a)) # output is P

Comments

1
public static String input = "10 5 5 10 6 6 2 3 1 3 4 5 3";

public static void uniqueValue (String numbers) {
    String [] str = input.split(" ");
    Set <String> unique = new HashSet <String> (Arrays.asList(str));
    System.out.println(unique);

    for (String value:unique) {
        int count = 0;
        for ( int i= 0; i<str.length; i++) {
            if (value.equals(str[i])) {
                count++;
            }
        }
        System.out.println(value+"\t"+count);
    }
}
public static void main(String [] args) {
    uniqueValue(input);
}

Comments

1

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<Character> set1=new HashSet<Character>();
    HashSet<Character> set2=new HashSet<Character>();

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

}

Comments

0

I would store all the characters of the string in an array that you will loop through to check if the current characters appears there more than once. If it doesn't, then add it to temp.

public static void uniqueCharacters(String test) {
    String temp = "";
    char[] array = test.toCharArray();
    int count; //keep track of how many times the character exists in the string

    outerloop: for (int i = 0; i < test.length(); i++) {
        count = 0; //reset the count for every new letter
        for(int j = 0; j < array.length; j++) {
            if(test.charAt(i) == array[j])
                count++;
            if(count == 2){
                count = 0;
                continue outerloop; //move on to the next letter in the string; this will skip the next two lines below
            }
        }
        temp += test.charAt(i);
        System.out.println("Adding.");
    }    
    System.out.println(temp);
}

I have added comments for some more detail.

Comments

0
import java.util.*;
import java.lang.*;
class Demo
{
public static void main(String[] args)
{

Scanner sc=new Scanner(System.in);
System.out.println("Enter String");
String s1=sc.nextLine();
 try{
HashSet<Object> h=new HashSet<Object>();
for(int i=0;i<s1.length();i++)
{
h.add(s1.charAt(i));
}
Iterator<Object> itr=h.iterator();
  while(itr.hasNext()){
   System.out.println(itr.next());
    }
    }
    catch(Exception e)
    {
    System.out.println("error");
    }
}
}

2 Comments

Can you add some explanation? Thanks!
HashSet does not support duplicate value I added each of characters to hashset so duplicates would get automatically resolved.
0

If you don't want to use additional space:

    String abc="developer";

    System.out.println("The unique characters are-");

    for(int i=0;i<abc.length();i++)
    {
        for(int j=i+1;j<abc.length();j++)
        {
            if(abc.charAt(i)==abc.charAt(j))
                abc=abc.replace(String.valueOf(abc.charAt(j))," ");
        }
    }   
    System.out.println(abc);

Time complexity O(n^2) and no space.

Comments

0

This String algorithm is used to print unique characters in a string.It runs in O(n) runtime where n is the length of the string.It supports ASCII characters only.

static String printUniqChar(String s) {
    StringBuilder buildUniq = new StringBuilder();
    boolean[] uniqCheck = new boolean[128];
    for (int i = 0; i < s.length(); i++) {
        if (!uniqCheck[s.charAt(i)]) {
            uniqCheck[s.charAt(i)] = true;
            if (uniqCheck[s.charAt(i)])
                buildUniq.append(s.charAt(i));
        }
    }

1 Comment

Code only answers arent encouraged as they dont provide much information for future readers please provide some explanation to what you have written
0
public class UniqueCharactersInString {


 public static void main(String []args){

    String input = "aabbcc";
    String output = uniqueString(input);

    System.out.println(output);
 }

 public static String uniqueString(String s){
     HashSet<Character> uniques = new HashSet<>();
     uniques.add(s.charAt(0));
     String out = "";
     out += s.charAt(0);

     for(int i =1; i < s.length(); i++){
         if(!uniques.contains(s.charAt(i))){
             uniques.add(s.charAt(i));
             out += s.charAt(i);
         }
     }
     return out;
 }
}

What would be the inneficiencies of this answer? How does it compare to other answers?

1 Comment

Code only answers are really discouraged. To help future readers, please explain what you are doing too!
0

Based on your desired output you can replace each character already present with a blank character.

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);
      } else {
         temp.replace(String.valueOf(temp.charAt(i)), "");
      }
 }

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

}

Comments

0
public void uniq(String inputString) {
    String result = "";
    int inputStringLen = inputStr.length();
    int[] repeatedCharacters = new int[inputStringLen];
    char inputTmpChar;
    char tmpChar;

    for (int i = 0; i < inputStringLen; i++) {
        inputTmpChar = inputStr.charAt(i);
        for (int j = 0; j < inputStringLen; j++) {
            tmpChar = inputStr.charAt(j);
            if (inputTmpChar == tmpChar)
                repeatedCharacters[i]++;
        }
    }

    for (int k = 0; k < inputStringLen; k++) { 
        inputTmpChar = inputStr.charAt(k);
        if (repeatedCharacters[k] == 1)
            result = result + inputTmpChar + " ";
    }

    System.out.println ("Unique characters: " + result);
}

In first for loop I count the number of times the character repeats in the string.
In the second line I am looking for characters repetitive once.

Comments

0

how about this :)

for (int i=0; i< input.length();i++)
    if(input.indexOf(input.charAt(i)) == input.lastIndexOf(input.charAt(i)))
        System.out.println(input.charAt(i) + "  is unique");

Comments

0

package extra;

public class TempClass {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String abcString="hsfj'pwue2hsu38bf74sa';fwe'rwe34hrfafnosdfoasq7433qweid";
        char[] myCharArray=abcString.toCharArray();
        TempClass mClass=new TempClass();

        mClass.countUnique(myCharArray);
        mClass.countEach(myCharArray);
    }
    /**
     * This is the program to find unique characters in array.
     * @add This is nice.
     * */
    public void countUnique(char[] myCharArray) {
        int arrayLength=myCharArray.length;
        System.out.println("Array Length is: "+arrayLength);
        char[] uniqueValues=new char[myCharArray.length];
        int uniqueValueIndex=0;
        int count=0;
        for(int i=0;i<arrayLength;i++) {
            for(int j=0;j<arrayLength;j++) {
                if (myCharArray[i]==myCharArray[j] && i!=j) {
                    count=count+1;
                }
            }
            if (count==0) {
                uniqueValues[uniqueValueIndex]=myCharArray[i];
                uniqueValueIndex=uniqueValueIndex+1;
                count=0;
            }
            count=0;
        }
        for(char a:uniqueValues) {
            System.out.println(a);
        }
    }
    /**
     * This is the program to find count each characters in array.
     * @add This is nice.
     * */
    public void countEach(char[] myCharArray) {

    }
}

1 Comment

Add an explanation to help the users to understand where actually the issue is.
0

Here str will be your string to find the unique characters.

function getUniqueChars(str){
let uniqueChars = '';
for(let i = 0; i< str.length; i++){
  for(let j= 0; j< str.length; j++) {
    if(str.indexOf(str[i]) === str.lastIndexOf(str[j])) {
       uniqueChars += str[i];
     }
   }
 }
 return uniqueChars;    

}

Comments

0
public static void main(String[] args) {
    String s = "aaabcdd";
    char a[] = s.toCharArray();
    List duplicates = new ArrayList();
    List uniqueElements = new ArrayList();
    for (int i = 0; i < a.length; i++) {
        uniqueElements.add(a[i]);
        for (int j = i + 1; j < a.length; j++) {
            if (a[i] == a[j]) {
                duplicates.add(a[i]);
                break;
            }
        }
    }
    uniqueElements.removeAll(duplicates);
    System.out.println(uniqueElements);
    System.out.println("First Unique : "+uniqueElements.get(0));

}

Output : [b, c] First Unique : b

Comments

0
import java.util.*;
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){
     for(int i=0;i<test.length();i++){
         if(test.lastIndexOf(test.charAt(i))!=i)
         test=test.replaceAll(String.valueOf(test.charAt(i)),"");
     }
  System.out.println(test);
}

}

1 Comment

Please provide additional details in your answer. As it's currently written, it's hard to understand your solution.
0

public class Program02 {

public static void main(String[] args)
{   
    String inputString = "abhilasha";
    
    for (int i = 0; i < inputString.length(); i++)
    {
        for (int j = i + 1; j < inputString.length(); j++)
        {
            if(inputString.toCharArray()[i] == inputString.toCharArray()[j])
            {
                inputString = inputString.replace(String.valueOf(inputString.charAt(j)), "");
            }
        }
    }
    
    System.out.println(inputString);
}

}

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.