在另一个数组中找到一个数组(byte )?

在另一个byte []中找到byte []的最简单方法是什么? 我有一种感觉,我可以用linq做,但我不知道如何。

注意:我用[c#]搜索并没有找到任何东西,我感到很惊讶。

这是一个简单(天真?)的方法:

 static int search(byte[] haystack, byte[] needle) { for (int i = 0; i <= haystack.Length - needle.Length; i++) { if (match(haystack, needle, i)) { return i; } } return -1; } static bool match(byte[] haystack, byte[] needle, int start) { if (needle.Length + start > haystack.Length) { return false; } else { for (int i = 0; i < needle.Length; i++) { if (needle[i] != haystack[i + start]) { return false; } } return true; } } 

这是Ergwun出色答案的更快版本:

 static int SearchBytes( byte[] haystack, byte[] needle ) { var len = needle.Length; var limit = haystack.Length - len; for( var i = 0; i <= limit; i++ ) { var k = 0; for( ; k < len; k++ ) { if( needle[k] != haystack[i+k] ) break; } if( k == len ) return i; } return -1; } 

在一个11MB干草堆和9字节针的简短测试中,这大约快了三倍。

优化是:

  • 每次通过外循环都没有函数调用。
  • 针脚长度和搜索限制被缓存。
  • match()开头的冗余长度测试被删除。

当然对于长字节数组,你想要使用类似Boyer-Moore搜索的东西,但是出于很多目的,这样的简单算法已经足够好了,它具有简短易懂和validation的优点。

使用lambda表达式尝试这个:

 private bool CheckPatternInArray(byte[] array, byte[] pattern) { int fidx = 0; int result = Array.FindIndex(array, 0, array.Length, (byte b) => { fidx = (b == pattern[fidx]) ? fidx + 1 : 0; return (fidx == pattern.Length); }); return (result >= pattern.Length - 1); } 

如果您追求最快的,请在此处查看解决方案。

你可能自己想过这个,但有时我喜欢做简单的事情。

 bool found = false; int i = 0; for(; i < byteArray.Length || found; i++) { if(byteArray[i] == lookingFor) { found = true; } }