How to Split String in VB.NET? There are different ways to call Split function in VB.NET. Below solutions guide you VB.NET Split string/sentence with examples.
Solution 1:
Simple Split Example. Below example uses Split on String.
' Input string
Dim str As String = "This is a test string"
' Split string based on spaces
Dim words As String() = str.Split(New Char() {" "c})
' Use For Each loop over words and display them. See the result below in Output.
Dim word As String
For Each word In words
Console.WriteLine(word)
Next
Solution 2:
Split Parts of a file path in VB.NET. Below example that splits file path.
' file system path we need to split
Dim str As String = "C:\Users\TestUser\Documents\Doc"
' Split the string on the backslash character (\)
Dim parts As String() = str.Split(New Char() {"\"c})
' Loop through result strings with For Each.
Dim part As String
For Each part In parts
Console.WriteLine(part)
Next
Solution 3:
Split string or sentence base on words in VB.NET
There are cases where you need to extract the words from a string/sentence in VB.NET. Below solution can handle non-word characters differently than the String Split method. For the same we need to use Regex.Split to parse the words in a string.
Add below line on top of your page.
Imports System.Text.RegularExpressions
Below code will splits words in VB.NET
Dim str As String
Dim arr As String() = SplitWordsInString("Oh! this is a simple task.")
For Each str In arr
Console.WriteLine(str)
Next
Console.ReadLine()
Private Function SplitWordsInString (ByVal str As String) As String()
Return Regex.Split(str, "\W+")
End Function