String
CharsHow can we access the first, second or last characters from a String
in the VB.NET programming language? There are some techniques to do this without exceptions.
With the index 0, we can access the first character. Each successive index contains the next character—so 1 is the second Char
.
This program written in the VB.NET language accesses some chars from a String
. The String
"abc" contains 3 characters.
char
by using an expression with the index 0. Chars (like arrays) are zero-indexes in VB.NET.char
is at the index 0. It is possible for any access that is out-of-range to throw an exception.char
in a String
of length 1 or more is located at the Length
minus one. This won't work on an empty string
.Char
at an index, we can wrap the test inside an If
-statement.string
's data.Module Module1 Sub Main() Dim value As String = "abc" ' Part 1: get first char. Dim first As Char = value(0) Console.WriteLine($"FIRST: {first}") ' Part 2: get second char. Dim second As Char = value(1) Console.WriteLine($"SECOND: {second}") ' Part 3: get last char. Dim last As Char = value(value.Length - 1) Console.WriteLine($"LAST: {last}") ' Part 4: safely check indexes. Dim target As Integer = 5 If target < value.Length Dim result As Char = value(target) Console.WriteLine($"TARGET: {result}") End If ' Part 5: we must access a char within the valid range of indexes. Try Dim result As Char = value(target) Catch ex As Exception: Console.WriteLine(ex) End Try End Sub End ModuleFIRST: a SECOND: b LAST: c System.IndexOutOfRangeException: Index was outside the bounds of the array. at System.String.get_Chars(Int32 index) at vbtest.Module1.Main() in C:\Users\...\Program.vb:line 26
Strings in VB.NET are indexed starting at zero and proceeding to one minus the length. Empty strings contain no characters, and an If
-statement can be used to detect valid indexes.