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

What is the easiest way to find byte [] inside another byte []? I have a feeling that I can do it with linq, but I don't know how to do it.

Note. I performed a search with help [c#]and did not find anything, I am surprised.

+5
source share
4 answers

Here's a simple (naive?) Way to do this:

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;
    }
}
+7
source

Here's a faster version of Ergwun's excellent answer :

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

In a short test with an 11-megabyte hay and a 9-byte needle, this was about three times faster.

Optimization:

  • No function call every time through an external loop.
  • Needle length and search limit are cached.
  • ​​ match().

, - Boyer-Moore, , , , , .

+18

-:

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);
}

, .

0

, , , .

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

All Articles