Search Array In Array - CSharp System

CSharp examples for System:Array Search

Description

Search Array In Array

Demo Code


using System.Linq;

public class Main{
        public static int SearchArrayInArray(byte[] haystack, byte[] needle, int startPos, int endPos)
      {//from   w ww. j  ava  2s.  c  o m
         var lookup = new int[256];
         for (var i = 0; i < lookup.Length; i++)
         {
            lookup[i] = needle.Length;
         }

         for (var i = 0; i < needle.Length; i++)
         {
            lookup[needle[i]] = needle.Length - i - 1;
         }

         var index = needle.Length - 1;
         var lastByte = needle.Last();
         while (index < haystack.Length)
         {
            if (index < startPos || index > endPos)
            {
               index++;
               continue;
            }

            var checkByte = haystack[index];
            if (haystack[index] == lastByte)
            {
               var found = true;
               for (var j = needle.Length - 2; j >= 0; j--)
               {
                  if (haystack[index - needle.Length + j + 1] != needle[j])
                  {
                     found = false;
                     break;
                  }
               }

               if (found)
                  return index - needle.Length + 1;
               else
                  index++;
            }
            else
            {
               index += lookup[checkByte];
            }
         }
         return -1;
      }
}

Related Tutorials