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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.