Unexpected Result From Split/ToArray

I’m parsing a UTF-8 string that looks like this:

$Item$
Some text
More Text

$Item$
Some text
More text

When I do

Items() = Source.Split("$Item$")

Split returns the correct number of fields (Items), but they’re all empty strings :open_mouth:

Is Split unable to handle a string containing EndOfLines?

I would expect the array members to still have the EndOfLines in them so it might appear blank in the variable viewer in the debugger or in a TextField.

They are actually zero length.

Huh. I wouldn’t expect that at all.

Do you have a sample you can share?

Curiouser and curiouser…

I made an example project and again after executing Split the fields are all zero length in the debugger.

But when added to a text area, the content magically appears!

Seems maybe an IDE bug?

What are the value of fields 1, 2 and 3? are those zero length too?

All fields are shown as zero length in the debugger.

EDIT: I am stupid, and did not look carefully enough at the other fields after checking field(0).

If your text starts with “$Item$”, the first element of your array will be empty, and the second element will start with a newline. Could that be what you are seeing?

I’m not worried about off-by-one errors at this point. Was just surprised that the debugger shows all fields as zero length. I guess I’ll carry on coding and see if it works, since the fields in the example program have content despite what the debugger shows.

Woops, apologies. @AlbertoD and @Kem_Tekinay both identified the issue, thanks!

1 Like

You might also want to remove the first "$Item$, and then trim each field to remove leading and trailing return characters and whitepspaces.

s = s.Trim

If s.Left(6) = "$Item$" Then
  //remove first one so you don't start with a blank field
  s = s.Right(s.Length - 6)
End If

fields = s.Split("$Item$")

For i As Integer = 0 To fields.LastIndex
  fields(i) = fields(i).Trim
Next