Remove Entries from Array starting from specific character

720 Views Asked by At

I have an array list that I need to modify to get rid of all the entries starting from the word that contains the period and earlier.

For example :

arrayList(0)= My
arrayList(1)= Name
arrayList(2) = Is
arrayList(3) = David.
arrayList(4) = How
arrayList(5) = Are

I need to remove arrayList(0-3)

I tried using:

dim pIndex = arrayList.LastIndexOf(arraylist.contains("."))
arrayList.RemoveRange(0,pIndex)

but just returns pIndex=-1 (meaning it can't be found)

How can I get the index of the entry with a period?

2

There are 2 best solutions below

1
On BEST ANSWER

LastIndexOf returns the index of a specific element. contains return True or False if the list contains or not the element yo pass as parameter. Following your example, arrayList.contains(".") returns False because none of the elements of the list is "."; then arrayList.LastIndexOf(false) returns -1 because none of the elements of the list is False.

You need to iterate throught the list:

arrayList(0) = "My"
arrayList(1) = "Name"
arrayList(2) = "Is"
arrayList(3) = "David."
arrayList(4) = "How"
arrayList(5) = "Are"

Dim pIndex As Integer
For pIndex = arrayList.Capacity - 1 To 0 Step -1
    If arrayList(pIndex).ToString.Contains(".") Then Exit For
Next

If pIndex <> -1 Then arrayList.RemoveRange(0, pIndex + 1)

(Not tested, but it should do the work)

0
On

Why ArrayList? If you use a List(Of String) then have much nicer tools at your disposal:

    Dim L As New List(Of String)
    L.Add("My")
    L.Add("Name")
    L.Add("Is")
    L.Add("David.")
    L.Add("How")
    L.Add("Are")

    Dim index As Integer = L.FindLastIndex(Function(x)
                                               Return x.Contains(".")
                                           End Function)
    If index <> -1 Then
        L.RemoveRange(0, index + 1)
    End If

    For i As Integer = 0 To L.Count - 1
        Debug.Print(i & ": " & L(i))
    Next