Java: printing a unique character in a string

I am writing a program that will print a unique character in a string (entered through a scanner). I created a method that tries to accomplish this, but I keep getting characters that don't repeat, instead of a character (or characters) that is unique to the string. I want only unique letters.

Here is 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 is an example output with the above code:

 Enter a word: nreena nrea 

Expected Result: ra

+5
source share
14 answers

Based on your desired result, you should replace the character that was originally added when it is duplicated later, therefore:

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

How to apply the KISS principle:

 public static void uniqueCharacters(String test) { System.out.println(test.chars().distinct().mapToObj(c -> String.valueOf((char)c)).collect(Collectors.joining())); } 
+4
source

Although for the approach to the solution, I suggest you try and use a better data structure, not just a string. However, you can simply change your logic to remove existing duplicates using 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
source

The accepted answer will not pass the entire test case, for example

input - "aaabcdd"

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

because the character is present an odd number of times.

Here I used ConcurrentHasMap to store the character and the number of occurrences of the character, and then deleted the character if the occurrences more than once.

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

This is an interview question. Find out all the unique characters of the string. Here is the complete solution. The code itself speaks for itself.

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

I would save all the characters of the string in an array that you swipe to check if the current characters are displayed more than once. If not, 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 added comments for more details.

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

If you do not want to use the extra 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); 

The complexity of the time is O (n ^ 2) and the space.

0
source

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"); 
0
source

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

 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)); } } 
0
source
 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 will be the disadvantages of this answer? How does this compare with other answers?

0
source

Depending on the desired result, you can replace each existing character with a blank one.

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

}

0
source
 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 the first for loop, I count the number of times a character repeats in a string.
In the second line, I look for duplicate characters once.

0
source

Source: https://habr.com/ru/post/1260614/


All Articles