Home

Search

VB.NET Substring Examples

Use the Substring Function to get parts of strings. Review the arguments to Substring.

Substring. This function gets parts of a String. It receives 2 arguments. These indicate the start index, and the length, of the character data.

Substring details. Substring() returns a new String instance containing the range of characters. It throws Exceptions on invalid arguments.

First example. Here we use Substring to get several characters of an input string. We start at index 1, and continue for 2 chars—the result string has 2 chars.
Tip: A new String is returned. We can easily manipulate this object. We print the string with Console.WriteLine.
Console
Info: Substring can be used with a start index and a length that is greater than zero to acquire the middle characters.
VB.NET program that uses Substring Module Module1 Sub Main() ' Specify a string literal. ' ... Then use Substring to take a middle substring. ' ... Index 1: letter "k." Dim literal As String = "jklmn" Dim substring As String = literal.Substring(1, 2) Console.WriteLine("RESULT: {0}", substring) End Sub End Module Output RESULT: kl

One argument. Next we call the Substring function with a single argument. Substring will internally copy all the string data at that index and following that index.
Tip: When we use Substring with one argument, the return value contains all the character data starting at, and following, that index.
VB.NET program that uses Substring with one argument Module Module1 Sub Main() ' Use this string literal. ' ... Next, use the Substring method with one parameter. Dim literal As String = "CatDogFence" Dim substring As String = literal.Substring(6) Console.WriteLine("Substring: {0}", substring) End Sub End Module Output Substring: Fence

Relative indexes. We can base the arguments to Substring on the result of the Length property of the original string minus some constant.
Info: This allows some functions to handle more input strings, reducing the amount of special-casing required.
Tip: This is a way you can base the length of the Substring on the length of the original string, providing more flexible code.
VB.NET program that uses Substring with Length arguments Module Module1 Sub Main() ' Use Length to handle relative indexes. Dim literal As String = "CatDogFence" Dim substring As String = literal.Substring(3, literal.Length - 5 - 3) Console.WriteLine("Middle string: {0}", substring) End Sub End Module Output Middle string: Dog

Null Substring. If our String may be null, we should test it with a function like String.IsNullOrEmpty before calling Substring. Consider this program—it causes an exception.String.IsNullOrEmpty
Version 1: Here we have code that does not crash—it tests the String for Nothing, and the code inside the If-statement does not run.
Version 2: This code causes the NullReferenceException. We cannot take a Substring of a null (Nothing) String.
Exception
VB.NET program that causes NullReferenceException Module Module1 Sub Main() Dim data As String = Nothing ' Version 1: this is safe. If Not String.IsNullOrEmpty(data) Then Console.WriteLine(data.Substring(1)) End If ' Version 2: this will fail. Dim result = data.Substring(1) End Sub End Module Output Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.

IndexOf and Substring. These functions are made to be used together. Suppose we have a label inside a string, and we want to get the string part following that label.
Part 1: We use IndexOf to search for the separator that follows the label. This returns the index of the separator.
IndexOf
Part 2: If the separator was found, its index is a positive number. We get the Substring at this index, adding in the separator's length.
Tip: It is important to add in the length of the separator string—otherwise, we will have the separator at the start of our substring.
VB.NET program that uses IndexOf and Substring Module Module1 Sub Main() Dim data As String = "Item: 123 X" ' Part 1: get the index of a separator with IndexOf. Dim separator As String = ": " Dim separatorIndex = data.IndexOf(separator) ' Part 2: see if separator exists. ' ... Get the following part with Substring. If separatorIndex >= 0 Then Dim value As String = data.Substring(separatorIndex + separator.Length) Console.WriteLine("RESULT: {0}", value) End If End Sub End Module Output RESULT: 123 X

First words. To get the first words from a String, we can count word separators (like spaces) in a For-loop. Then we take a Substring to get just those words.
Here: The FirstWords method counts spaces in the input string. Once the required number is reached, a Substring is returned.
Words: The correct number of words are present in the output. There are 5 and 3 words in the result strings.
VB.NET program that gets first words from string Module Module1 Public Function FirstWords(input As String, count As Integer) As String Dim words = count For i As Integer = 0 To input.Length - 1 ' Decrement word count when we reach a space. If input(i) = " " Then words -= 1 End If ' When no words remaining, return a substring to this point. If words = 0 Then Return input.Substring(0, i) End If Next Return "" End Function Sub Main() ' Test our FirstWords method. Dim example1 = "This is an example summary that we are using." Console.WriteLine(FirstWords(example1, 5)) Dim example2 = "How many words are in this sentence?" Console.WriteLine(FirstWords(example2, 3)) End Sub End Module Output This is an example summary How many words

Right. In some programs a Function that calls Substring in a special way may be helpful. Here we see a Right method. It returns a substring located on the right side of a string.
Arguments: The first argument is the string to take the substring from. And the second is the length of the substring part.
VB.NET program that uses substring in Right method Module Module1 Function Right(value As String, length As Integer) As String ' Get rightmost characters of specified length. Return value.Substring(value.Length - length) End Function Sub Main() ' Test the Right function. Dim phrase1 As String = "cat and dog" Dim result1 As String = Right(phrase1, 3) Console.WriteLine(result1) End Sub End Module Output dog

One Char. We can get a one-char string with the Substring function. But for this special case, we can just access a Char from the String, which is much faster. No allocation is needed.
VB.NET program that uses one-char substrings Module Module1 Sub Main() Dim value As String = "CAT" ' Get a one-char substring as a Char. ' ... This is faster. Dim middle1 As Char = value(1) Console.WriteLine(middle1) ' Get a one-char substring as a String. Dim middle2 As String = value.Substring(1, 1) Console.WriteLine(middle2) End Sub End Module Output A A

Benchmark, one char. Avoiding Substring when possible is probably the most important optimization here. Substring() is a String function that does significant work.
Version 1: Here we access the last Char in a string. We test the Char against the character literal "m."
Version 2: In this version of the code we call Substring to get a 1-char string containing the last character.
Result: It is many times faster to access the Char, and test it directly, without calling Substring.
VB.NET program that times one-char Substring Module Module1 Sub Main() Dim data As String = "arm" Dim m As Integer = 10000000 ' Version 1: test last char of String. Dim s1 As Stopwatch = Stopwatch.StartNew For i As Integer = 0 To m - 1 Dim lastChar = data(data.Length - 1) If lastChar <> "m"c Then Return End If Next s1.Stop() ' Version 2: test last 1-char Substring of String. Dim s2 As Stopwatch = Stopwatch.StartNew For i As Integer = 0 To m - 1 Dim lastCharString = data.Substring(data.Length - 1) If lastCharString <> "m" Then Return End If Next s2.Stop() Dim u As Integer = 1000000 Console.WriteLine(((s1.Elapsed.TotalMilliseconds * u) / m).ToString("0.00 ns")) Console.WriteLine(((s2.Elapsed.TotalMilliseconds * u) / m).ToString("0.00 ns")) End Sub End Module Output 0.88 ns One-char access 21.35 ns One-char substring

String copying. Let us consider Substring's internal implementation. When we call the Substring function, a new string copy is made. A reference to this string data is returned.
Note: When we assign to the result of the Substring function, we are performing a bitwise copy of only that reference.
Also: In some algorithms, using strings that already exist is much faster than creating substrings.

Mid. VB.NET has special support for the Mid built-in statement. With Mid, we can get a substring or assign to a substring based on start and length arguments.Mid Statement

Between substrings. Sometimes a simple parser may need to find substrings between, before and after other ones. Some functions can be used to implement this useful logic.Between, Before, After

A review. Substring copies a series of characters from a source string into a new string that is allocated upon the managed heap. It is called with 1 or 2 arguments.

Home
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.