Java 如何在不重复的情况下打印字符数组中的字符?
我被要求编写一个程序来打印字符数组中的值。此数组包含重复的值,但输出不应包含重复的字符。请勿使用Set。这就是我所创造的。让我知道是否有任何其他有效的方法来做同样的事情Java 如何在不重复的情况下打印字符数组中的字符?,java,Java,我被要求编写一个程序来打印字符数组中的值。此数组包含重复的值,但输出不应包含重复的字符。请勿使用Set。这就是我所创造的。让我知道是否有任何其他有效的方法来做同样的事情 public class RemoveDuplication { public static void main (String[] args){ char[] a= new char[]{'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c'};
public class RemoveDuplication {
public static void main (String[] args){
char[] a= new char[]{'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c'};
String s=Character.toString(a[0]);
for (int i=1; i<a.length; i++) {
if ((s.indexOf(a[i])) == -1) {
s = s + Character.toString(a[i]);
} else {
}
}
// if you want character array as result
char[] result = s.toCharArray();
System.out.println(result);
}
}
公共类移除复制{
公共静态void main(字符串[]args){
char[]a=新字符[]{'a','b','c','a','b','c','a','b','c','a','b','c'};
字符串s=字符.toString(a[0]);
因为(inti=1;i你做得太过分了
只需选择:
StringBuilder builder = new StringBuilder().append(a[0]);
然后将append()
添加到该生成器对象;最后,调用builder.toString()
。而不是使用s
字符串变量执行所有有趣的操作
您的代码在字符串和字符之间来回移动,并使用+进行字符串追加,正如所说的那样;非常复杂。如果您使用Set对象,它将为您完成这一任务
Set<Character> s = new HashSet<>();
s.add('c');
s.add('c');
//c was only added once
对字符进行流式处理,只过滤到不同的代码点,然后在StringBuilder
中收集代码点,最后将其打印出来:
System.out.println(
str.chars().distinct().boxed()
.collect(Collector.of(StringBuilder::new,
StringBuilder::appendCodePoint,
StringBuilder::append)));
每次听到独特元素,我都会想到集合。下面是使用集合
最简单的实现:
char[] a= new char[]{'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c'};
Set<Character> set = new HashSet<Character>(); //declare Set of Character type
for(char c : a)
set.add(c); //Add chars in 'a' to the set
System.out.println(set);
char[]a=新字符[]{'a','b','c','a','b','c','a','b','c','a','b','c'};
Set Set=new HashSet();//声明字符类型的集合
用于(字符c:a)
set.add(c);//将“a”中的字符添加到集合中
系统输出打印项次(套);
输出:[a、b、c]
您可以做些什么来加速这一过程,例如,使用二进制搜索检查字符C是否在输出的字符数组A中(而不是打印)。如果字符C不在列表中,则打印字符C,然后将字符C插入(排序)到A中(以便能够使用二进制搜索)。System.out.println(Arrays.toString(result))
Hi Elliott,谢谢你的建议。请注意,我们重载了“println”方法,它接受字符数组作为参数,并在字符数组中打印值列表。是的!这是一个很好的解决方案,但我不允许使用Set:(是的!谢谢你的建议,伙计(y)非常欢迎您……有趣的是:我假设您不允许使用集合,这就是为什么我没有提到该部分;因为您已经获得该部分以正确查找重复项;-)嗨,如何知道给定的字符是否已经存在于字符串生成器对象中。如果((s.indexOf(a[I])==-1)如果s是StringBuilder,则这行代码无效。您可以始终执行以下操作:builder.toString().indexOf(),tooOh,似乎在我键入答案时,问题被编辑为“请勿使用集合”。因为它已经发布了,如果它仍然存在,我认为这很好。
char[] a= new char[]{'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c'};
Set<Character> set = new HashSet<Character>(); //declare Set of Character type
for(char c : a)
set.add(c); //Add chars in 'a' to the set
System.out.println(set);