Extended ByteArarySearcher API

This commit is contained in:
Philip Helger
2024-07-09 17:18:36 +02:00
parent fb7fe28eca
commit 7483a0e0d6
2 changed files with 51 additions and 18 deletions

View File

@@ -5,24 +5,33 @@ public final class ByteArraySearcher {
private ByteArraySearcher() {
}
public static int indexOf(byte[] haystack, byte[] needle) {
if (needle.length > haystack.length) {
return -1;
}
// Any needle to search?
if (needle.length == 0) {
return -1;
}
for (int i = 0; i <= haystack.length - needle.length; i++) {
boolean found = true;
for (int j = 0; j < needle.length; j++) {
if (haystack[i + j] != needle[j]) {
found = false;
break;
}
}
if (found) {
return i;
}
}
return -1;
}
public static boolean contains(byte[] haystack, byte[] needle) {
if (needle.length > haystack.length) {
return false;
}
for (int i = 0; i <= haystack.length - needle.length; i++) {
boolean found = true;
for (int j = 0; j < needle.length; j++) {
if (haystack[i + j] != needle[j]) {
found = false;
break;
}
}
if (found) {
return true;
}
}
return false;
return indexOf (haystack, needle) >= 0;
}
}