在另一个byte []中找到byte []的最简单方法是什么?我有一种感觉,我可以用linq做,但我不知道如何.
注意:我做了搜索[c#]
并没有找到任何东西,我很惊讶.
Mic*_*ary 20
这是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;
}
Run Code Online (Sandbox Code Playgroud)
在使用11MB干草堆和9字节针的简短测试中,这大约快了三倍.
优化是:
match()
删除开头的冗余长度测试.当然对于长字节数组,你想要使用类似Boyer-Moore搜索的东西,但是出于很多目的,这样的简单算法已经足够好了,它具有简短易懂和验证的优点.
这是一个简单(天真?)的方法:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
11936 次 |
最近记录: |