我试图在一个字节数组中连续查找一个字节数组(byte []),并且发现了一个仅找到第一个匹配项的代码。
在这里找到代码: 在另一个数组中找到一个数组(byte [])?
问题:如何使用下面的代码连续查找字节数组?
public int SearchBytes(byte[] haystack, byte[] needle)
{
int len = needle.Length;
int limit = haystack.Length - len;
for (int i = 0; i <= limit; i++)
{
int k = 0;
for (; k < len; k++)
{
if (needle[k] != haystack[i + k]) break;
}
if (k == len) return i;
}
return -1;
}
您可以像这样更改方法以接受起始索引:
public int SearchBytes(byte[] haystack, byte[] needle, int start_index)
{
int len = needle.Length;
int limit = haystack.Length - len;
for (int i = start_index; i <= limit; i++)
{
int k = 0;
for (; k < len; k++)
{
if (needle[k] != haystack[i + k]) break;
}
if (k == len) return i;
}
return -1;
}
区别仅在于此方法接受astart_index
并在此特定索引处开始搜索。
现在,您可以像这样使用它:
byte[] haystack = new byte[] { 1, 2, 3, 4, 5, 1, 2, 3 };
byte[] needle = new byte[] {1,2,3};
int index = 0;
while (true)
{
index = SearchBytes(haystack, needle, index);
if (index == -1)
break;
Console.WriteLine("Found at " + index);
index += needle.Length;
}
该循环从索引0开始,然后使用上一次搜索的结果来设置新索引以开始下一个搜索。
它添加needle.Length
到索引中,以便我们在先前找到的结果结束后立即开始搜索。
更新:
可以使用以下代码创建一个将索引作为数组返回的方法:
public int[] SearchBytesMultiple(byte[] haystack, byte[] needle)
{
int index = 0;
List<int> results = new List<int>();
while (true)
{
index = SearchBytes(haystack, needle, index);
if (index == -1)
break;
results.Add(index);
index += needle.Length;
}
return results.ToArray();
}
可以这样使用:
byte[] haystack = new byte[] { 1, 2, 3, 4, 5, 1, 2, 3 };
byte[] needle = new byte[] {1,2,3};
int[] indexes = SearchBytesMultiple(haystack, needle);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句