繁体   English   中英

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

[英]Find an array (byte[]) inside another array?

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

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

这是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 haystack 和 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;
    }
}

使用 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;
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM