Monday, 6 February 2012

VB.NET Split String Examples


You need to Split a String in your VB.NET program based on a character delimiter such as " "c. Often, input String data needs to be parsed and separated based on a certain character. With the examples in this document, we review ways to call the Split function effectively.

Split example

To start, here we see how you can split a VB.NET String based on a space character, " "c. We allocate a New Char() array as well as a String() array to store the words in. Finally, we loop over the Strings and display them to the Console.
Program that uses Split on String [VB.NET]

Module Module1

    Sub Main()
 ' We want to split this input string
 Dim s As String = "there is a cat"

 ' Split string based on spaces
 Dim words As String() = s.Split(New Char() {" "c})

 ' Use For Each loop over words and display them
 Dim word As String
 For Each word In words
     Console.WriteLine(word)
 Next
    End Sub

End Module

Output

there
is
a
cat

Split parts of file path

Here we see how you can Split a file system path into separate parts using Visual Basic .NET. We use a New Char() array with one string, "\""c, and then loop through and display the results.
Program that splits file path [VB.NET]

Module Module1

    Sub Main()
 ' The file system path we need to split
 Dim s As String = "C:\Users\Sam\Documents\Perls\Main"

 ' Split the string on the backslash character
 Dim parts As String() = s.Split(New Char() {"\"c})

 ' Loop through result strings with For Each
 Dim part As String
 For Each part In parts
     Console.WriteLine(part)
 Next
    End Sub

End Module

Output

C:
Users
Sam
Documents
Perls
Main

Split based on words

Often you need to extract the words from a String or sentence in VB.NET. The code here needs to handle punctuation and non-word characters differently than the String Split method. Here we use Regex.Split to parse the words.
Program that splits words [VB.NET]

Imports System.Text.RegularExpressions

Module Module1

    Sub Main()
 ' Declare iteration variable
 Dim s As String

 ' Loop through words in string
 Dim arr As String() = SplitWords("That is a cute cat, man!")

 ' Display each word. Note that punctuation is handled correctly.
 For Each s In arr
     Console.WriteLine(s)
 Next
 Console.ReadLine()
    End Sub

    ''' <summary>
    ''' Split the words in string on non-word characters.
    ''' This means commas and periods are handled correctly.
    ''' </summary>
    Private Function SplitWords(ByVal s As String) As String()
 '
 ' Call Regex.Split function from the imported namespace.
 ' Return the result array.
 '
 Return Regex.Split(s, "\W+")
    End Function

End Module

Output

That
is
a
cute
cat
man
Description of the example code. In the Main() subroutine you can see that two variables are declared. The second variable is a String() array that receives the results from the Private Function next.
Description of the Regex. The Function shown in the example calls the Regex.Split method, which can be accessed with dot notation, with no instance necessary. The second parameter to the method is a regular expression pattern.
Regex.Split UseYou need to Split a String in your VB.NET program based on a character delimiter such as " "c. Often, input String data needs to be parsed and separated based on a certain character. With the examples in this document, we review ways to call the Split function effectively.

Split example

To start, here we see how you can split a VB.NET String based on a space character, " "c. We allocate a New Char() array as well as a String() array to store the words in. Finally, we loop over the Strings and display them to the Console.
Program that uses Split on String [VB.NET]

Module Module1

    Sub Main()
 ' We want to split this input string
 Dim s As String = "there is a cat"

 ' Split string based on spaces
 Dim words As String() = s.Split(New Char() {" "c})

 ' Use For Each loop over words and display them
 Dim word As String
 For Each word In words
     Console.WriteLine(word)
 Next
    End Sub

End Module

Output

there
is
a
cat

Split parts of file path

Here we see how you can Split a file system path into separate parts using Visual Basic .NET. We use a New Char() array with one string, "\""c, and then loop through and display the results.
Program that splits file path [VB.NET]

Module Module1

    Sub Main()
 ' The file system path we need to split
 Dim s As String = "C:\Users\Sam\Documents\Perls\Main"

 ' Split the string on the backslash character
 Dim parts As String() = s.Split(New Char() {"\"c})

 ' Loop through result strings with For Each
 Dim part As String
 For Each part In parts
     Console.WriteLine(part)
 Next
    End Sub

End Module

Output

C:
Users
Sam
Documents
Perls
Main

Split based on words

Often you need to extract the words from a String or sentence in VB.NET. The code here needs to handle punctuation and non-word characters differently than the String Split method. Here we use Regex.Split to parse the words.
Program that splits words [VB.NET]

Imports System.Text.RegularExpressions

Module Module1

    Sub Main()
 ' Declare iteration variable
 Dim s As String

 ' Loop through words in string
 Dim arr As String() = SplitWords("That is a cute cat, man!")

 ' Display each word. Note that punctuation is handled correctly.
 For Each s In arr
     Console.WriteLine(s)
 Next
 Console.ReadLine()
    End Sub

    ''' <summary>
    ''' Split the words in string on non-word characters.
    ''' This means commas and periods are handled correctly.
    ''' </summary>
    Private Function SplitWords(ByVal s As String) As String()
 '
 ' Call Regex.Split function from the imported namespace.
 ' Return the result array.
 '
 Return Regex.Split(s, "\W+")
    End Function

End Module

Output

That
is
a
cute
cat
man
Description of the example code. In the Main() subroutine you can see that two variables are declared. The second variable is a String() array that receives the results from the Private Function next.
Description of the Regex. The Function shown in the example calls the Regex.Split method, which can be accessed with dot notation, with no instance necessary. The second parameter to the method is a regular expression pattern.

Description of the Regex pattern.
 The pattern "\W+" is used, and this means "1 or more non-word characters". This pattern will match punctuation and spaces. Therefore, all those characters will be used as delimiters.

Split each line in file

Here we see one way to Split each line in a file using File.ReadAllLines and Split. We have a comma-separated-values CSV file, and want to print out each value and its row number. Here is the input file "example.txt". Please see the below example.
The Split code example follows. It first reads in the file with ReadAllLines. This function puts each line in the file into an array element. The example next Splits on ","c. The final comment shows the output of the program.
Input file used

frontal,parietal,occipital,temporal
pulmonary artery,aorta,left ventricle

Example program that splits lines [VB.NET]

Imports System.IO

Module Module1
    Sub Main()
 Dim i As Integer = 0

 ' Loop through each line in array returned by ReadAllLines
 Dim line As String
 For Each line In File.ReadAllLines("example.txt")

     ' Split line on comma
     Dim parts As String() = line.Split(New Char() {","c})

     ' Loop over each string received
     Dim part As String
     For Each part In parts
  ' Display to Console
  Console.WriteLine("{0}:{1}", i, part)
     Next
     i += 1
 Next
    End Sub
End Module

Output

0:frontal
0:parietal
0:occipital
0:temporal
1:pulmonary artery
1:aorta
1:left ventricle

Summary

We saw some ways to Split your String in Visual Basic .NET, getting a String() array that you can use in a For Each loop. We used Split on different characters; used Regex.Split for a more complex pattern example; and finally dealt with a CSV file.
Description of the Regex pattern. The pattern "\W+" is used, and this means "1 or more non-word characters". This pattern will match punctuation and spaces. Therefore, all those characters will be used as delimiters.

Split each line in file

Here we see one way to Split each line in a file using File.ReadAllLines and Split. We have a comma-separated-values CSV file, and want to print out each value and its row number. Here is the input file "example.txt". Please see the below example.
The Split code example follows. It first reads in the file with ReadAllLines. This function puts each line in the file into an array element. The example next Splits on ","c. The final comment shows the output of the program.
Input file used

frontal,parietal,occipital,temporal
pulmonary artery,aorta,left ventricle

Example program that splits lines [VB.NET]

Imports System.IO

Module Module1
    Sub Main()
 Dim i As Integer = 0

 ' Loop through each line in array returned by ReadAllLines
 Dim line As String
 For Each line In File.ReadAllLines("example.txt")

     ' Split line on comma
     Dim parts As String() = line.Split(New Char() {","c})

     ' Loop over each string received
     Dim part As String
     For Each part In parts
  ' Display to Console
  Console.WriteLine("{0}:{1}", i, part)
     Next
     i += 1
 Next
    End Sub
End Module

Output

0:frontal
0:parietal
0:occipital
0:temporal
1:pulmonary artery
1:aorta
1:left ventricle

1 comment:

  1. Thank you so much for the post you do. I like your post and all you share with us is up to date and quite informative, i would like to bookmark the page so i can come here again to read you, as you have done a wonderful job. psiprograms.com

    ReplyDelete