Home
VB.NET
String Substring Examples
This page was last reviewed on Feb 16, 2024.
Dot Net Perls
Substring. This VB.NET function gets parts of a String. It receives 2 arguments—these indicate the start index, and the length, of the character data.
This String function returns a new String instance containing the range of characters. Substring() will throw an Exception 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.
Info Substring can be used with a start index and a length that is greater than zero to acquire the middle characters.
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
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.
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
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.
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
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.
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.
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
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.
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.
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
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.
Detail The correct number of words are present in the output. There are 5 and 3 words in the result strings.
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
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.
Argument 1 The first argument to the Right() function is the string to take the substring from.
Argument 2 This is the length of the substring part (characters are counted from the right).
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
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.
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
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. This remains true on .NET 7 in 2022.
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
0.88 ns One-char access 21.35 ns One-char substring
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 16, 2024 (edit).
Home
Changes
© 2007-2024 Sam Allen.