2017-02-25 62 views
2

我被要求编写一个程序在字符数组中打印值。该数组包含重复的值,但输出不应包含重复的字符。 请勿使用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'}; 
    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); 
    } 
} 
+1

'System.out.println(Arrays.toString(result));' –

+1

嗨艾略特,感谢您的建议。 请注意,我们重载了'println'方法,它接受char数组作为参数并打印char数组中的值列表。 – Vicky

回答

1

你在做什么。

只是去:

StringBuilder builder = new StringBuilder().append(a[0]); 

,然后append()该生成器对象;并最终;请致电builder.toString()。而不是你用那个s字符串变量做的所有有趣的事情。

你的代码是从字符串和字符之间来回和使用+作为字符串追加是说;非常复杂的事情。

+0

是的!感谢你的建议哥们(y) – Vicky

+0

非常欢迎你......有趣的事情:我认为你不会被允许使用一套,这就是为什么我没有提到那部分;因为你已经有了这个部分找到正确的重复;-) – GhostCat

+0

嗨,如何知道给定的字符已经存在的字符串生成器对象。 ((s.indexOf(a [i]))== -1)如果s是StringBuilder,这行代码无效。 – Vicky

1

如果你使用Set对象,它会为你做到这一点。

Set<Character> s = new HashSet<>(); 
s.add('c'); 
s.add('c'); 
//c was only added once 

然后重复这样的:

for(Character c: s) 
{ 
    System.out.println(c); 
} 
+0

Yeahh!其伟大的解决方案,但我不被允许使用设置:( – Vicky

0

流的特点,过滤器只不同的代码点,然后收集代码点在StringBuilder,最后打印出来:

System.out.println(
    str.chars().distinct().boxed() 
     .collect(Collector.of(StringBuilder::new, 
        StringBuilder::appendCodePoint, 
        StringBuilder::append))); 
0

每次我听到独特要素,出现在我的脑海里。因此,这里是使用sets最简单的实现:

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

OUTPUT:A,B,C]

+0

哦,似乎这个问题被编辑说**不使用sets **当我输入答案。自从它已经发布,我认为它很好,如果它遗迹。 –

0

,你可以做些什么来加速比这有点像,检查角色C在输出的字符数组A(不是打印)使用二进制搜索。如果字符C不在列表中,则打印字符C,然后将字符C插入(排序)到A(以便能够使用二分查找)。

相关问题