Powered by Blogger.

Sub Strings in Visual Basic .NET

You often manipulate strings by using a set of characters that appears at the start, at the end, or a set that appears somewhere in between. Those sets are called substrings.


The Substring method allows you to grab a set of characters from any position in the string and can be used in two ways.

The first way is to give it a starting point/index and a number of characters to grab (length of the string data).


In this example we instruct it to start at character position 0 (the beginning of the string), and grab the next 5 characters:


1
2
3
Dim MyString As String = "Hello World!"
Dim substring As String = MyString.Substring(0, 5)
MessageBox.Show(substring) ' = Hello                 

The other way is calling Substring method with a single argument.

When you're providing only one parameter it tells the Substring to start at the given position and copy everything right up to the end of the string data.

In this example we instruct it to grab everything at the index 6 and following that index:

1
2
3
Dim MyString As String = "Hello World!"
Dim substring As String = MyString.Substring(6)
MessageBox.Show(substring) ' = World!