Neil Sedaka was wrong apparently - Breaking up isn’t hard to do :-)
Intro
There are a couple of useful little enhancements to the Split method in VB2005.
I can’t begin to count how many times I’ve suggested the use of this very handy method in VB.NET answers over the years. You know the kind of thing – you have a string containing words or phrases which are separated by commas, for example, and you want to break it up into its constituent parts using the comma as the delimiter.
Dim Address As String = "Mead Manor,Codeville,Dumfries,DG1 GD1"
You can use Split like this:
Dim MyInfo() As String = Address.Split(",")
For Each s As String In MyInfo
Debug.WriteLine(s)
Next
To get:
Mead Manor
Codeville
Dumfries
DG1 GD1
Or you can home in on a particular element, e.g.
Debug.WriteLine("Postcode: " & MyInfo(3))
Verse 1: Delimiters
In both the 2003 and 2005 versions you can have multiple delimiters. I often used to forget that in VB2003 you had to create an array of chars for this:
Dim Seps() As Char = {",", " ", ";"}
and my attempts to bully it into accepting an array of strings was doomed to failure:
Dim Seps() As String = {",", " ", ";"} ‘ rejected by the code editor
The good news in VB2005 is that you can now use either type of array – char or string – and the Split function will play along quite happily.
Chorus: Empty Elements
If you use this approach with the following string:
Dim InputStr As String = ("Wet, Dry ,, Calm;Windy ")
Dim MyInfo() As String = InputStr.Split(Seps)
you will find that you have several empty elements, which while being correct may not always be what you wanted. The resulting output in VB.NET 2003 would be:
Wet
Dry
Calm
Windy
And what you really wanted was:
Wet
Dry
Calm
Windy
Step forward the very useful StringSplitOptions Enumeration in VB2005!
The additional overloaded version which takes a StringSplitOptions Enum as a second parameter:
MyInfo = InputStr.Split(Seps, StringSplitOptions.RemoveEmptyEntries)
will produce exactly the result you want:
Wet
Dry
Calm
Windy
Finale
It may not be earth-shattering stuff, but sometimes it’s these little things that make all the difference in keeping the frustration factor down to manageable levels!