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

时间:2019-03-13 19:53:06

标签: 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;
    }
}

2 个答案:

答案 0 :(得分:0)

尝试一下:我已经更新了代码,该代码将返回所有匹配的大小写,并且如果您需要第一个或最后一个,则可以编写:方法中的index.First()或index.last。

    public IEnumerable<int> FindArray(int[] array, int[] subArray)
    {
        IEnumerable<int> index = Enumerable.Range(0, array.Length - subArray.Length + 1);
        for (int i = 0; i < subArray.Length; i++)
        {
            index = index.Where(n => array[n + i] == subArray[i]).ToArray();
        }
        return index;
    }

答案 1 :(得分:0)

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