[英]Check if primitive array contains another array
有沒有簡單的方法來檢查一個數組是否包含Java中的另一個數組?
基本上,我想做這樣的事情:
private static final String NOT_ALLOWED;
public boolean isPasswordOkay(char[] password){
return new String(password).contains(NOT_ALLOWED);
}
...但是沒有將密碼轉換為String
, Sun表示可能存在安全風險 。 是否有一種更簡潔的方法,而不是手動迭代數組的每個元素?
如果您使用Guava ,您可以定義這樣的方法:
public static boolean contains(final char[] array, final char[] target){
return Chars.indexOf(array, target)>=0;
}
參考:
如果你不想使用Guava,這里是我的方法和Guava的合並版本:
public static boolean contains(final char[] array, final char[] target){
// check that arrays are not null omitted
if (target.length == 0) {
return true;
}
outer:
for (int i = 0; i < array.length - target.length + 1; i++) {
for (int j = 0; j < target.length; j++) {
if (array[i + j] != target[j]) {
continue outer;
}
}
return true;
}
return false;
}
private static final String NOT_ALLOWED="...";
public boolean isPasswordOkay(char[] password){
StringBuilder sb = new StringBuilder(password);
boolean ret = sb.indexOf(NOT_ALLOWED) != -1;
sb.replace(0, sb.length(), " ");
return ret;
}
有一個聽起來像你想要的解決方案http://www.coderanch.com/t/35439/Programming/Intersection-two-arrays-交叉是這類事情的數學術語!
我找不到任何會這樣做的東西。 一個選項可能是使用Apache Collections並使用ArrayUtils子陣列方法創建子數組,然后在您創建的每個子數組上進行比較,迭代原始數組。
new String(password).matches(".*["+NOT_ALLOWED.replace(']','\\').replace("\\","\\\\\")+"].*");
要小心......你必須逃避一些不允許的角色,比如]
和\\
!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.