Implement IndexOf method without Framework

Array.IndexOf searches an array. It acts upon an array of any type in the C# language. It locates the offset of the value searched for. The IndexOf method on Array, in both its generic form and its LastIndexOf form, is useful in many program contexts.

   1: using System;

   2: using System.Collections.Generic;

   3: using System.Linq;

   4: using System.Text;

   5:  

   6: namespace IndexOF

   7: {

   8:     class Program

   9:     {

  10:  

  11:         private static int IndexOf(char[] chars1, char[] chars2)

  12:         {

  13:             if (chars1.Length < chars2.Length)

  14:                 return -1;

  15:  

  16:             int found = -1;

  17:             int j = 0;

  18:  

  19:             for (int i = 0; i < chars1.Length; i++)

  20:             {

  21:                 if (chars1[i] == chars2[j])

  22:                 {

  23:                     if (j == 0)

  24:                         found = i;

  25:  

  26:                     j++;

  27:                     if (j >= chars2.Length)

  28:                         return found;

  29:                 }

  30:                 else

  31:                 {

  32:                     j = 0;

  33:  

  34:                     if (found >= 0)

  35:                         i = found;

  36:                     found = -1;

  37:                 }

  38:             }

  39:             

  40:             return -1;

  41:         }

  42:  

  43:         static void Main(string[] args)

  44:         {

  45:             char[] arr1 = { 'v', 'a', 'b', 'c', 'd', 'e', 'f' };

  46:             char[] arr2 = { 'c', 'd', 'v'};

  47:  

  48:  

  49:             Console.WriteLine("index = {0}", IndexOf(arr1, arr2).ToString());

  50:  

  51:             Console.ReadKey();

  52:         }

  53:     }

  54: }

Advertisements