Reports the zero-based index of the first occurrence of the specified byte-array in this instance. The search starts at a specified position. - CSharp System

CSharp examples for System:Byte Array

Description

Reports the zero-based index of the first occurrence of the specified byte-array in this instance. The search starts at a specified position.

Demo Code

//  Licensed under the Apache License, Version 2.0 (the "License");
using System.Collections;
using System.Text;
using System;/* ww w.  ja v  a 2s  . com*/

public class Main{
    /// <summary>
      /// Reports the zero-based index of the first occurrence of the specified byte-array in this instance. The search starts at a specified position.
      /// </summary>
      /// <param name="array"></param>
      /// <param name="value">The bytes to find.</param>
      /// <param name="startIndex">The search starting position.</param>
      /// <returns>The zero-based index position of value if value is found, or -1 if it is not. Invalid paramaters result in a return a value of -1.</returns>
      public static int IndexOf(this byte[] array, byte[] value, int startIndex = 0)
      {
         if (array == null || value == null || value.Length == 0 || startIndex < 0 || startIndex >= array.Length)
            return -1;

         int i = startIndex;
         int j = 0;
         int k = 0;
         while (i < array.Length)
         {
            j = i;
            k = 0;
            while (k < value.Length && array[j] == value[k])
            {
               j++;
               k++;
            }
            if (k == value.Length)
            {
               return i;
            }
            i++;
         }

         return -1;
      }
        /// <summary>
      /// Reports the zero-based index of the first occurrence of the specified string in this instance. The search starts at a specified position.
      /// </summary>
      /// <param name="array"></param>
      /// <param name="value">The string to find.</param>
      /// <param name="startIndex">The search starting position.</param>
      /// <returns>The zero-based index position of value if value is found, or -1 if it is not. If value is null or a zero-length string, the return value is startIndex.</returns>
      public static int IndexOf(this byte[] array, string value, int startIndex = 0)
      {
         if (array == null || value == null || value.Length == 0 || startIndex < 0 || startIndex >= array.Length)
            return -1;

         byte[] byteValue = value.ToByteArray();
         return IndexOf(array, byteValue, startIndex);
      }
}

Related Tutorials