2017-05-20 28 views
-6

我有一个6字符长的字符串,我想检查一下,如果每个字符只有一个。如何?如果在String中有相同的字符,如何检查Java?

+2

请给例如输入和代码你试图用字符串处理,你可以在这里 –

+0

更广阔的解释:http://stackoverflow.com/questions/513832/how-do-i-compare-strings- in-java和https://www.tutorialspoint.com/java/java_strings.htm 和https://docs.oracle.com/javase/tutorial/java/data/manipstrings.html –

回答

0

您可以使用Set做到这一点。你需要独特的元素和保证你包含独特的元素。 HashSetSet的执行,你可以用它来实现这个想法。

public boolean ifAllCharsUnique(String input){ 
    char[] arr = input.toCharArray(); 
    int length = arr.length; 
    Set<Character> checker = new HashSet<>(); 
    for(int i =0 ; i < length; i++){ 
     if(checker.contains(arr[i]){ 
       return false; 
     } 
     checker.add(arr[i]); 
    } 
    return true; 
} 
+0

使用这种方法,我创建了一个只包含唯一字符的新数组(或ArrayList?)< checker >? – jaraipali

3

你可以明显不同的字符数比较字符串的长度:

boolean charMoreThanOnce = s.chars().distinct().count() < s.length(); 
+1

尽管我喜欢这样的漂亮,干净,准确的答案;我仍然觉得不高兴,因为这看起来很像你做了某人的作业。并不是说他可以从中获得很多,但仍然可以。 – GhostCat

+1

是否分裂毛发指出[它不适用于''“''(http://ideone.com/dyN8ym)? –

相关问题