【发布时间】:2016-04-27 18:00:00
【问题描述】:
我试图在一个字节数组中不断地找到一个字节数组(byte[]),但我找到了一个只找到第一次出现的代码。
这是我找到代码的地方: Find an array (byte[]) inside another array?
问题:如何使用下面的代码连续查找字节数组?
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;
}
【问题讨论】:
-
好吧,你试过什么?如果你想返回一个
List<int>的匹配项,难道你不能将return i更改为matches.Add(i)并声明一个List<int> matches = new List<int>()开始吗? -
连续查找是指找到一个字节序列与另一个字节数组的所有出现?
-
@Gnqz 是的,我就是这个意思。
-
看看the algorithm in this thread,得到正确答案。它使用 Boyer-Moore-Horspool 算法,速度非常快。
标签: c# arrays search find byte