2017-02-25 79 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(以便能夠使用二分查找)。