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.
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.
String
is returned. We can easily manipulate this object. We print the string
with Console.WriteLine
.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 ModuleRESULT: kl
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.
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 ModuleSubstring: Fence
We can base the arguments to Substring
on the result of the Length
property of the original string
minus some constant.
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 ModuleMiddle string: Dog
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
for Nothing, and the code inside the If
-statement does not run.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 ModuleUnhandled 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.
IndexOf
to search for the separator that follows the label. This returns the index of the separator.Substring
at this index, adding in the separator's length.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 ModuleRESULT: 123 X
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.
FirstWords
method counts spaces in the input string. Once the required number is reached, a Substring
is returned.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 ModuleThis is an example summary How many words
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
.
Right()
function is the string
to take the substring from.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 Moduledog
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 ModuleA A
char
Avoiding Substring
when possible is probably the most important optimization here. Substring()
is a String
function that does significant work.
Char
in a string
. We test the Char
against the character literal "m."Substring
to get a 1-char string
containing the last character.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
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.