从 Java 中的字符串中删除重复项 [英] Removing duplicates from a String in Java
问题描述
我正在尝试遍历一个字符串以删除重复的字符.
例如字符串 aabbccdef
应该变成 abcdef
并且字符串 abcdabcd
应该变成 abcd
这是我目前所拥有的:
公共类测试{公共静态无效主(字符串 [] args){String input = new String("abbc");字符串输出 = new String();for (int i = 0; i < input.length(); i++) {for (int j = 0; j
最好的方法是什么?
使用 Stream 使事情变得简单.
noDuplicates = Arrays.asList(myString.split("")).溪流().清楚的().collect(Collectors.joining());
<块引用>
这里有更多关于 Stream 的文档以及您可以使用的所有内容它 :https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html
描述"部分对 Streams 的好处非常有指导意义.
I am trying to iterate through a string in order to remove the duplicates characters.
For example the String aabbccdef
should become abcdef
and the String abcdabcd
should become abcd
Here is what I have so far:
public class test {
public static void main(String[] args) {
String input = new String("abbc");
String output = new String();
for (int i = 0; i < input.length(); i++) {
for (int j = 0; j < output.length(); j++) {
if (input.charAt(i) != output.charAt(j)) {
output = output + input.charAt(i);
}
}
}
System.out.println(output);
}
}
What is the best way to do this?
Using Stream makes it easy.
noDuplicates = Arrays.asList(myString.split(""))
.stream()
.distinct()
.collect(Collectors.joining());
Here is some more documentation about Stream and all you can do with it : https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html
The 'description' part is very instructive about the benefits of Streams.
这篇关于从 Java 中的字符串中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!