在 C# 中的数组中查找子数组

我试图在数组中找到子数组。它仅适用于一个子数组,但我希望如果有多个子数组,它会返回最后一个的索引。例如,对于 [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;

    }

}


跃然一笑
浏览 602回答 1
1回答

一只甜甜圈

public int FindLast(int[] haystack, int[] needle){&nbsp; &nbsp; // iterate backwards, stop if the rest of the array is shorter than needle (i >= needle.Length)&nbsp; &nbsp; for (var i = haystack.Length - 1; i >= needle.Length - 1; i--)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var found = true;&nbsp; &nbsp; &nbsp; &nbsp; // also iterate backwards through needle, stop if elements do not match (!found)&nbsp; &nbsp; &nbsp; &nbsp; for (var j = needle.Length - 1; j >= 0 && found; j--)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // compare needle's element with corresponding element of haystack&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; found = haystack[i - (needle.Length - 1 - j)] == needle[j];&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (found)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // result was found, i is now the index of the last found element, so subtract needle's length - 1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return i - (needle.Length - 1);&nbsp; &nbsp; }&nbsp; &nbsp; // not found, return -1&nbsp; &nbsp; return -1;}作为一个可运行的小提琴:https ://dotnetfiddle.net/TfjPuY
打开App,查看更多内容
随时随地看视频慕课网APP