Check if primitive array contains another array
Is there any easy way to check if one array contains another array in Java?
Essentially, I want to do something like this:
private static final String NOT_ALLOWED;
public boolean isPasswor开发者_Go百科dOkay(char[] password){
return new String(password).contains(NOT_ALLOWED);
}
...but without converting the password to a String
, which Sun indicates could be a security risk. Is there a neater method than manually iterating over every element of the array?
If you use Guava, you can define a method like this:
public static boolean contains(final char[] array, final char[] target){
return Chars.indexOf(array, target)>=0;
}
Reference:
Chars.indexOf(char[], char[])
And if you don't want to use Guava, here's the merged version of my method and Guava's:
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;
}
There is a solution that sounds like what you want at http://www.coderanch.com/t/35439/Programming/Intersection-two-arrays - Intersection is the maths-y term for this kind of thing!
I can't find anything that would do this. one option may be to use Apache Collections and use the ArrayUtils subarray methods to create sub-arrays and then compare on each one that you create, iterating through the original array.
new String(password).matches(".*["+NOT_ALLOWED.replace(']','\\').replace("\\","\\\\\")+"].*");
Beware... you have to escape some of your not allowed characters, like ]
and \
!
精彩评论