-2

I am writing a program to display only the unique characters in a string which is entered by the user through a Scanner.

For example, if the user enters the following line

eleven seven

Then my expected output will be

lvn svn

Here's my code:

import java.util.Arrays;
import java.util.Scanner;

public class unique_element {
    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        String str = sc.nextLine();
        char value = 0;

        String str1[] = str.split(" ");

        for (int k=0;k<str1.length;k++){
            char string[] = str1[k].toLowerCase().toCharArray();

            String temp = "";
            for(int i=0;i<string.length;i++){
                char current = string[i];
                if(temp.indexOf(current)<0){
                    temp = temp + current;
                }else{
                    temp = temp.replace(String.valueOf(current), "");
                }
            }
            System.out.print(temp+" ");
        }
    }
}

And here's sample output with the above code:

Eleven seven
lven svn 
Abra
  • 19,142
  • 7
  • 29
  • 41
It's me
  • 9
  • 4

5 Answers5

1

First create a hash map and add every char in your string.
Then increment the int value when the same char comes.

map.put(key, map.get(key) + 1);

should work.

Also check this: How to update a value, given a key in a hashmap?

0

Using java8 streams and the collectors framework

 String result=Arrays.stream("Eleven seven".toCharArray())
                     .distinct()
                     .map(ch->ch+"")
                     .collect(Collectors.joining());
Sync it
  • 1,180
  • 2
  • 11
  • 29
0

I adapt your solution a little bit. I changed the string concatenation a bit, so that a new string does not have to be created with every iteration. At the end I made the solution with indexOf and lastIndexOf. But I guess that there is a more efficient solution. This is the code:

String content = "Eleven seven";

String[] splittedContent = content.toLowerCase().split(" ");

for (String word: splittedContent) {
    char[] splittedWord = word.toCharArray();
    StringBuilder builder = new StringBuilder();

    for (char element: splittedWord) {
        int index = word.indexOf(Character.toString(element));
        int lastIndex = word.lastIndexOf(Character.toString(element));

        // only true if the character occurs once in the word
        if (index == lastIndex) {
            builder.append(element);
        }
    }

    System.out.print(builder.toString() + " ");
}

Otherwise there is another solution with the Java Stream API. I use the groupingBy method to create the map with single characters and their counting. At the end I filter the unique single characters and create a string. The solution is similar to the proposal of @Bora Çolakoğlu:

for (String s: content.toLowerCase().split(" ")) {
    // creating the map with single characters and their counting
    Map<String, Long> frequentChars = s.chars()
        .mapToObj(Character::toString)
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

    // filter unique single characters and join to string
    String unique = frequentChars.entrySet()
        .stream()
        .filter(v -> v.getValue() == 1L)
        .map(Map.Entry::getKey)
        .collect(Collectors.joining());

    System.out.println(unique);
}
flaxel
  • 4,173
  • 4
  • 17
  • 30
0

In Java 8 we can do something like this

private void removeduplicatecharactersfromstring() {
    String myString = "aabcd eeffff ghjkjkl";
    StringBuilder builder = new StringBuilder();
    System.out.println(myString);
    Arrays.asList(myString.split(" "))
            .forEach(s -> {
                builder.append(Stream.of(s.split(""))
                        .distinct().collect(Collectors.joining()).concat(" "));
            });
    System.out.println(builder); // abcd ef ghjkl
}
0

my question correct answer I got:

import java.util.Arrays;
import java.util.Scanner;

public class unique_element {
    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        String str = sc.nextLine();
        char value = 0;

        String str1[] = str.split(" ");
        System.out.println(Arrays.toString(str1));

        for (int k=0;k<str1.length;k++){

            char string[] = str1[k].toLowerCase().toCharArray();

            for (int i=0;i<string.length;i++){
                int count=0;
                for (int j=0;j<string.length;j++){
                    if(i!=j){
                        if(string[i]==string[j]){
                            count++;
                        }
                    }
                }

                if(count==0){
                    System.out.print(string[i]);
                }
            }
            System.out.print(" ");
            
        }

    }

}
It's me
  • 9
  • 4