给定一个字节数组,我如何在其中找到一个(较小的)字节数组的位置?
This documentation看起来很有希望,使用 ArrayUtils
,但如果我是正确的,它只会让我在要搜索的数组中找到一个单独的字节。
(我不认为这很重要,但以防万一:有时搜索字节数组将是常规 ASCII 字符,其他时候它将是控制字符或扩展 ASCII 字符。因此使用字符串操作并不总是合适的)
大数组可能在 10 到大约 10000 字节之间,而较小的数组大约为 10。在某些情况下,我会在一次搜索中在较大的数组中找到几个较小的数组。而且我有时会想要找到实例的最后一个索引而不是第一个。
最佳答案
最简单的方法是比较每个元素:
public int indexOf(byte[] outerArray, byte[] smallerArray) {
for(int i = 0; i < outerArray.length - smallerArray.length+1; ++i) {
boolean found = true;
for(int j = 0; j < smallerArray.length; ++j) {
if (outerArray[i+j] != smallerArray[j]) {
found = false;
break;
}
}
if (found) return i;
}
return -1;
}
一些测试:
@Test
public void testIndexOf() {
byte[] outer = {1, 2, 3, 4};
assertEquals(0, indexOf(outer, new byte[]{1, 2}));
assertEquals(1, indexOf(outer, new byte[]{2, 3}));
assertEquals(2, indexOf(outer, new byte[]{3, 4}));
assertEquals(-1, indexOf(outer, new byte[]{4, 4}));
assertEquals(-1, indexOf(outer, new byte[]{4, 5}));
assertEquals(-1, indexOf(outer, new byte[]{4, 5, 6, 7, 8}));
}
当您更新您的问题时:Java 字符串是 UTF-16 字符串,它们不关心扩展的 ASCII 集,因此您可以使用 string.indexOf()
关于java - 在另一个字节数组中查找一个字节数组的 indexOf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21341027/