Java:仅打印字符串中的唯一字符

huangapple go评论72阅读模式
英文:

Java: Only Print Unique Characters in a String

问题

我正在编写一个程序,用于显示用户通过Scanner输入的字符串中的唯一字符。

例如,如果用户输入以下行

eleven seven

那么我期望的输出将会是
lvn svn

以下是我的代码:

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

以下是使用上述代码的示例输出:

Eleven seven
lven svn 
英文:

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(&quot; &quot;);

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

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

And here's sample output with the above code:

Eleven seven
lven svn 

答案1

得分: 1

首先创建一个哈希映射,并将字符串中的每个字符添加进去。
然后在相同字符出现时增加整数值。

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

应该可以工作。

还可以查看这个链接:https://stackoverflow.com/questions/4157972/how-to-update-a-value-given-a-key-in-a-hashmap

英文:

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: https://stackoverflow.com/questions/4157972/how-to-update-a-value-given-a-key-in-a-hashmap

答案2

得分: 0

使用Java 8的流(streams)收集器框架(collectors framework)

String result = Arrays.stream("Eleven seven".toCharArray())
                     .distinct()
                     .map(ch -> ch + "")
                     .collect(Collectors.joining());
英文:

Using java8 streams and the collectors framework

 String result=Arrays.stream(&quot;Eleven seven&quot;.toCharArray())
                     .distinct()
                     .map(ch-&gt;ch+&quot;&quot;)
                     .collect(Collectors.joining());

答案3

得分: 0

我稍微调整了你的解决方案。我对string concatenation 进行了一些修改,以便不必在每次迭代时都创建新字符串。最后,我使用了 indexOflastIndexOf 来实现解决方案。但我猜可能还有更高效的解决方案。以下是代码:

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

        // 仅当字符在单词中只出现一次时为真
        if (index == lastIndex) {
            builder.append(element);
        }
    }

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

另外还有一种使用 Java Stream API 的解决方案。我使用 groupingBy 方法创建了包含单个字符及其计数的映射。最后,我筛选出唯一的单个字符并创建一个字符串。这个解决方案类似于 @Bora Çolakoğlu 提出的建议:

for (String s: content.toLowerCase().split(" ")) {
    // 创建包含单个字符及其计数的映射
    Map<String, Long> frequentChars = s.chars()
        .mapToObj(Character::toString)
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

    // 筛选出唯一的单个字符并拼接成字符串
    String unique = frequentChars.entrySet()
        .stream()
        .filter(v -> v.getValue() == 1L)
        .map(Map.Entry::getKey)
        .collect(Collectors.joining());

    System.out.println(unique);
}
英文:

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 = &quot;Eleven seven&quot;;

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

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

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(&quot; &quot;)) {
    // creating the map with single characters and their counting
    Map&lt;String, Long&gt; 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 -&gt; v.getValue() == 1L)
        .map(Map.Entry::getKey)
        .collect(Collectors.joining());

    System.out.println(unique);
}

答案4

得分: 0

在Java 8中,我们可以像这样做:

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
}
英文:

In Java 8 we can do something like this

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

答案5

得分: 0

我得到了正确的答案:

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

    }

}
英文:

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(&quot; &quot;);
        System.out.println(Arrays.toString(str1));

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

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

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

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

    }

}

huangapple
  • 本文由 发表于 2020年10月5日 00:57:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/64197421.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定