Split function behaviour...

  • Thread starter Thread starter Mobileboy36
  • Start date Start date
M

Mobileboy36

Hi group,

Look at this little piece of code:

Dim test As String
Dim Sepken As Char() = {Chr(13), Chr(10)}
Dim message As String = "123" & vbCrLf & "456"
Dim En As IEnumerator
En = message.Split(Sepken).GetEnumerator
While En.MoveNext
test = En.Current
End While
The split function seems to create an array with 3 elements:
"123", "" and "456".
The enumerator returns 3 value for en.current:
"123", "" and "456".

Where does the empty string come from?
Am I doing something wrong? Should I really use an if structure to filter
away the empty string?

Best regards,
Mobile Boy
 
If you look in the doc for Split[1], it specifically says "If two delimiters
are adjacent, or a delimiter is found at the beginning or end of this
instance, the corresponding array element contains Empty." so this seems
quite expected. If your data is \r\n delimited, use the overload that takes
in a string and pass vbCrLf in and not an array of chars.


--

Chris Tacke, Embedded MVP
OpenNETCF Consulting
Managed Code in an Embedded World
www.OpenNETCF.com

[1] http://msdn2.microsoft.com/en-us/library/b873y76a.aspx
 
HI,

this empty string appears, because you use as an parameter for split
method 2 chars: "\n" and "\r" and vbCrLf constant contains these 2
chars and split method in its behavior splits string when find one of
these chars and if there is nothing to return it returns empty
string.

You can always check if some string is not empty string.

I hope this will help you,

Regards,
M. Wolniewicz
 
Thank you for the clear answers group...it works!!
But: when you use strvar.split, there is only 1 version of the split
function available (with an array of chars as parameter)
When you use strings.split you have a way to pass a string as separator.

Thank you for the tip.
 
HI,

this empty string appears, because you use as an parameter for split
method 2 chars: "\n" and "\r" and vbCrLf constant contains these 2
chars and split method in its behavior splits string when find one of
these chars and if there is nothing to return it returns empty
string.

You can always check if some string is not empty string.

I hope this will help you,

Regards,
M. Wolniewicz
 
Back
Top