在C#中查找阵列中的子阵列

  • 本文关键字:阵列 查找 c# arrays
  • 更新时间 :
  • 英文 :


我试图在数组中找到子阵列。它仅适用于一个子阵列,但我希望,如果有一个以上的子阵列,它将返回最后一个索引。例如,对于[3,4,1,2,0,1,2,5,6],[1,2]应返回5.

public int FindArray(int[] array, int[] subArray)
    {
        //throw new NotImplementedException();
    int y=0;
    int index=0;
    bool find= false;
    for(int x=0;x< array.Length && y< subArray.Length;)
    {
        if(array[x]!= subArray[y])
        {
            if(find==true)
            {               
                y=0;
                index=x;
            }
            else
            {
                x++;                
                y=0;
                index=x;    
            }
        }
        else
        {
            find=true;
            x++;        
            y++;
        }
    }
    if(y==subArray.Length)
            return index;
    else
            return -1;
    }
}
public int FindLast(int[] haystack, int[] needle)
{
    // iterate backwards, stop if the rest of the array is shorter than needle (i >= needle.Length)
    for (var i = haystack.Length - 1; i >= needle.Length - 1; i--)
    {
        var found = true;
        // also iterate backwards through needle, stop if elements do not match (!found)
        for (var j = needle.Length - 1; j >= 0 && found; j--)
        {
            // compare needle's element with corresponding element of haystack
            found = haystack[i - (needle.Length - 1 - j)] == needle[j];
        }
        if (found)
            // result was found, i is now the index of the last found element, so subtract needle's length - 1
            return i - (needle.Length - 1);
    }
    // not found, return -1
    return -1;
}

作为可运行的小提琴:https://dotnetfiddle.net/tfjpuy

最新更新