Question Search an array for another array

Pirahnaplant

Well-known member
Joined
Mar 29, 2009
Messages
75
Programming Experience
3-5
Basically I want to find the first occurrence of one array in another. I have tried using the Array.IndexOf Function, but it always returns -1.
Example:
VB.NET:
Dim array1 As Byte() = {1, 2, 3, 4, 5}
Dim array2 As Byte() = {2, 3}
MsgBox(Array.IndexOf(array1, array2))
Even though array2 does exist in array1, the message box always shows -1
 
Even though array2 does exist in array1
There is no item in array1 that equals array2, what you mean is that the item sequence of array2 exists in array1. It is not too difficult to write a function that loops and checks if a sequence of elements of one array exists in another and returns the index. Here's a try:
VB.NET:
Public Shared Function FindSequence(Of T)(ByVal first() As T, ByVal second() As T, Optional ByVal start As Integer = 0) As Integer
    For index As Integer = start To (first.Length - second.Length)
        If Object.Equals(first(index), second(0)) Then
            Dim tmp(second.Length - 1) As T
            Array.ConstrainedCopy(first, index, tmp, 0, second.Length)
            If tmp.SequenceEqual(second) Then
                Return index
            End If
        End If
    Next
    Return -1
End Function
VB.NET:
Dim ix = FindSequence(array1, array2) ' = 1
 
Back
Top