且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

找到另一个阵列里的数组(字节[])?

更新时间:2023-08-29 12:40:04

下面是一个简单的(幼稚?)的方式来做到这一点:

Here's a simple (naive?) way to do it:

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