Lesson 10 - Strings in VB.NET - Split and Join
In the previous exercise, Solved tasks for Visual Basic .NET lesson 9, we've practiced our knowledge from previous lessons.
Lesson highlights
Are you looking for a quick reference on split and join in VB.NET instead of a thorough-full lesson? Here it is:
Using String
methods
(insert/remove/substring):
{VBNET_CONSOLE}
Console.WriteLine("I would banish all of these Internets.".Insert(8, "not "))
Console.WriteLine("I would not banish all of these Internets.".Remove(8, 4))
Console.WriteLine("I would not banish all of these Internets.".Substring(2, 5))
Console.WriteLine("alpha".CompareTo("bravo"))
{/VBNET_CONSOLE}
Using the Split()
and
Join()
methods:
{VBNET_CONSOLE}
Dim text As String = "I like VB.NET"
Dim words() = text.Split(" ") ' split the text by spaces
Console.WriteLine(words(2)) ' print the third word
words(1) = "love" ' change the second word
text = String.Join(" ", words) ' join it back to the text
Console.WriteLine(text)
{/VBNET_CONSOLE}
Would you like to learn more? A complete lesson on this topic follows.
In the previous tutorial, Solved tasks for Visual Basic .NET lesson 9, we made clear that Visual Basic .NET
strings are essentially arrays of characters. In today's lesson, we're going to
explain other String
methods that I have intentionally kept from
you because we didn't know that string
s are similar to arrays
We can call many methods which we know from arrays in a similar fashion. For
example: First()
, Last()
, IndexOf()
and
others.
When you create an arbitrary variable and write a dot after it, Visual Studio will show us all of the available methods, properties, and variables, that we can call on that variable (we'll go deeper into this in the OOP course). This tool is called IntelliSense and it'll make our work easier and complete a code for us. Let's try it out:

The same suggestion can also be accessed by pressing Ctrl + Spacebar when the text cursor is on the dot. Of course, this applies to all variables and classes (we'll use it further along the way, as well). The methods are ordered alphabetically and we can list them using the arrow keys. VS shows us the description of the methods, what they do, and what parameters do they need.
Let's talk about the following methods and demonstrate them on simple examples:
Additional String methods
Insert()
Inserts a substring into a String at a specified position. The parameters are the position in the String and the substring.
{VBNET_CONSOLE}
Console.WriteLine("I would banish all of these Internets.".Insert(8, "not"))
{/VBNET_CONSOLE}
The output:
Console application
I would not banish all of these Internets.
Remove()
Removes characters from the given position to the end of the String. The parameter is the numerical position. We can also enter a second parameter which specifies the number of characters we want to be removed.
{VBNET_CONSOLE}
Console.WriteLine("I would not banish all of these Internets.".Remove(8, 4))
{/VBNET_CONSOLE}
The output:
Console application
I would banish all of these Internets.
Substring()
Returns a substring from the given position to the end of the String. We can enter the second parameter which specifies the length of the substring.
{VBNET_CONSOLE}
Console.WriteLine("I would not banish all of these Internets.".Substring(2, 5))
{/VBNET_CONSOLE}
The output:
Console application
would
CompareTo()
It allows us to compare two strings alphabetically. Returns -1
if the first String is before the String in the parameter, 0
if
they are equal and 1
if the String is after one in the
parameter:
{VBNET_CONSOLE}
Console.WriteLine("alpha".CompareTo("bravo"))
{/VBNET_CONSOLE}
The output:
Console application
-1
Now let's look at two more, very useful, String
methods.
Split()
and Join()
From the previous tutorial, we know that parsing strings character by
character can be rather complicated. Even though we made a fairly simple
example. Of course, we'll encounter strings all the time, both in user inputs,
e.g. from the console or from input fields in windows form applications, and in
TXT and XML files. Very often, we're given one long String
, a line
in a file or in the console, in which there are multiple values separated by
separators, e.g. commas. In this case, we're talking about the CSV format
(Comma-Separated Values). To be sure that we all know what we're talking about,
let's look at some sample strings:
Jessie,Brown,Wall Street 10,New York,130 00 .. ... .-.. .- -. -.. ... --- ..-. - (1,2,3;4,5,6;7,8,9)
- The first string clearly represents a user. We could, for example, store users into a CSV file (one per line).
- The second string is Morse code characters and uses the space character as the separator.
- The third string is a matrix of 3 columns and 3 rows. The column separator is a comma, whereas the row separator is a semicolon.
We can call the Split()
method on a String
, which
takes a separator, Char
, or even an array of separators as a
parameter. It'll then split the original String using separators into an array
of substrings and return it. This will greatly simplify value extraction from
strings for our current intents and purposes.
The Join()
method is called directly on the String
data type and vice versa allows us to join an array of substrings into a single
String using a specified separator. The parameters are an array and a separator.
The output of the method is the resulting String.
Right then, let's see what we've got up until now. We still don't know how to declare objects, users, or even work with multidimensional arrays, i.e. matrices. Nevertheless, we want to make something cool, so we'll settle with making a Morse code message decoder.
Morse code decoder
We'll start out by preparing the program structure, as always. We need two
strings for the messages, one for a message in Morse code, the other one will be
empty for now and we'll store the results of our efforts there. Next, we need
letter definitions (as we had with vowels). Of course, we'll also need the Morse
code versions of the letter definitions. We can store letters as a single
String
since they only consist of one character. The Morse code
letters consist of multiple characters, therefore we have to specify them using
an array.
The structure of our program should now look something like this:
' the String which we want to decode Dim s As String = ".. -.-. - ... --- -.-. .. .- .-.." Console.WriteLine("The original message: {0}", s) ' the String with a decoded message Dim message As String = "" ' array definitions Dim alphabetChars As String = "abcdefghijklmnopqrstuvwxyz" Dim morseChars() = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."}
We could also add other Morse characters such as numbers and punctuation
marks, but we won't worry about them for now. We'll split the String
s
with the Split()
method into an array of substrings
containing the Morse characters. We'll split it by the space character. Then
we'll iterate over the array using a For Each
loop:
' splitting the String into Morse characters Dim characters() = s.Split(" ") ' iterating over Morse characters For Each morseChar As String In characters Next
Ideally, we should somehow deal with cases when the user enters e.g. multiple
spaces between characters (users often do things of the sort). In this case,
Split()
creates one more empty substring in the array. We should
then detect it in the loop and ignore it, but we won't deal with that in this
lesson.
In the loop, we'll attempt to find the current Morse character in the
morseChars
array. We'll be interested in its index
because when we look at that same index in the alphabetChars
array,
there will be the corresponding letter. This is mainly because both the array
and the String contain the same characters which are ordered alphabetically.
Let's place the following code into the loop's body:
Dim alphabetChar As Char = "?" Dim index As Integer = Array.IndexOf(morseChars, morseChar) If index >= 0 Then ' character was found alphabetChar = alphabetChars(index) End If message &= alphabetChar
First, the alphabetical character is set to "?"
since it may
very well be that we don't have it defined in our array. Then we try to
determine its index. If it succeeds, we assign the character from alphabetic
characters at its index to alphabetChar
. Finally, we add the
character to the message. The &=
operator works the same as
message = message & alphabetChar
.
Now, we'll print the message and add ReadKey()
:
{VBNET_CONSOLE}
' a String which we want to decode
Dim s As String = ".. -.-. - ... --- -.-. .. .- .-.."
Console.WriteLine("The original message: {0}", s)
' a String with a decoded message
Dim message As String = ""
' array definitions
Dim alphabetChars As String = "abcdefghijklmnopqrstuvwxyz"
Dim morseChars() = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....",
"..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-",
"...-", ".--", "-..-", "-.--", "--.."}
' splitting a String into Morse characters
Dim characters() = s.Split(" ")
' iteration over Morse characters
For Each morseChar As String In characters
Dim alphabetChar As Char = "?"
Dim index As Integer = Array.IndexOf(morseChars, morseChar)
If index >= 0 Then ' character was found
alphabetChar = alphabetChars(index)
End If
message &= alphabetChar
Next
Console.WriteLine("The decoded message: {0}", message)
Console.ReadKey()
{/VBNET_CONSOLE}
The output:
Console application
The original message: .. -.-. - ... --- -.-. .. .- .-..
The decoded message: ictsocial
Done! If you want to train some more, you can create a program which would
encode a String to the Morse code. The code would be very similar. We'll use the
Split()
and Join()
methods several more times
throughout our courses.
Special characters and escaping
Strings can contain multiple lines or special characters as e.g. tabulators.
We break lines using the vbCrLf
constant and insert tabulators
using vbTab
.
Let's test them out:
{VBNET_CONSOLE}
'First option
Console.WriteLine("First line{0}Second line", vbCrLf)
'Second option
Console.WriteLine("First line" & vbCrLf & "Second line")
'They both work the same
Console.ReadKey()
{/VBNET_CONSOLE}
VB.NET inserts 2 characters in the String
- CR and LF. If you
were exploring the ASCII table, you probably know that these are characters
number 13
and 10
. Breaking lines by those 2 characters
originated from old printers which needed 2 commands to be sent - Carriage
Return and Line Feed to move the printer carriage back to the start and move the
paper down to the next line.
You can achieve the same by inserting those characters manually:
{VBNET_CONSOLE}
'First option
Console.WriteLine("First line{0}Second line", Chr(13) & Chr(10))
'Second option
Console.WriteLine("First line" & Chr(13) & Chr(10) & "Second line")
'They both work the same
Console.ReadKey()
{/VBNET_CONSOLE}
If you happen to need to declare quotes in a String, you need to escape them with another quotes so VB.NET wouldn't misinterpret it as the end of the String:
{VBNET_CONSOLE}
Console.WriteLine("This is a quotation mark: """)
{/VBNET_CONSOLE}
Today we basically finished the on-line course on the VB.NET language basic
structures. In the next lesson, Solved tasks for Visual Basic .NET lesson 10, we'll look at a bonus episode about
multidimensional arrays and we'll briefly talk about the Math
class
and advanced console control. Nothing will surprise you from the basic language
constructs anymore In fact,
you could potentially start working with objects now, but I would suggest for
you to read the next few lesson. You all still have a long way to go, but your
future looks bright!
In the following exercise, Solved tasks for Visual Basic .NET lesson 10, we're gonna practice our knowledge from previous lessons.
Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.
Download
By downloading the following file, you agree to the license terms
Downloaded 21x (52.05 kB)
Application includes source codes in language VB.NET