您可以更改方法接受起始索引是这样的:
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;
}
的差别只是在于这个方法接受一个start_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
添加到索引,以便我们在先前找到的结果结束后立即开始搜索。
UPDATE:
下面是该代码是如何可以被用来创建一个返回的索引作为阵列的方法:
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);
嘛,你尝试过什么?如果你想返回一个匹配列表'',你不能只是将'return i'改为'matches.Add(i)'宣布了一个'List matches = new List ()' ? –
通过不断发现你的意思是找到与另一个字节数组的所有字节序列的出现? – Gnqz
@Gnqz是的,这就是我的意思。 –