String Chars. How 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.
Part 5 An exception is thrown when we access an index that does not occur within the 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
Summary. 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.
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.