Search code examples
vb.netsplitstring-function

Split("", "|") returns 1 item


When I do the following....

    Dim s As String = ""
    Dim sLines() As String = s.Split("|", StringSplitOptions.None)

...

sLines.Count is 1.

Why?

There is nothing to split, and the string to be split is empty, so I would expect sLines.Count to be 0.

Thank you.


Solution

  • A sort of consistency: if "a|b" split on | is ["a", "b"] and "a" split on | is ["a"], it makes some sense for "|b" split on | to be ["", "b"] and "" split on | to be [""].

    You can remove all empty entries by passing StringSplitOptions.RemoveEmptyEntries instead of None, or just check for s = String.Empty manually otherwise.