Alex Gordon
Alex Gordon

Reputation: 60751

vb.net: why is this starting at 0?

    Dim myDelims As String() = New String() {"<beginning of record>"}
    Dim split1 As String() = temp_string.Split(myDelims, StringSplitOptions.None)

    For Each s As String In split1
        If InStr(s, lot__no) Then

for some reason, the first s in split1 is giving a value of "". there's nothing in it. why is it starting ONE before the first element?

Upvotes: 0

Views: 71

Answers (1)

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422006

You need to pass StringSplitOptions.RemoveEmptyEntries to filter out empty strings.

By default, the String.Split method will split the string by the delimiter. If the string starts with the delimiter, it's basically composed of an empty string, the delimiter, and the remaining part of the string.

Dim s = "!Hello!World!"
Dim delimiters = {"!"}
Dim arr = s.Split(delimiters, StringSplitOptions.RemoveEmptyEntries)
Array.ForEach(arr, AddressOf Console.WriteLine) ' // Prints out the result

In this example, arr will contain two elements, "Hello" and "World". Without RemoveEmptyEntires, it would have contained four elements, "", "Hello", "World", and "".

Upvotes: 1

Related Questions