您可以更改方法接受起始索引是這樣的:
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是的,這就是我的意思。 –