Home
VB.NET
String Chars (Get Char at Index)
This page was last reviewed on Jun 19, 2024.
Dot Net Perls
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.
Loop, String Chars
With the index 0, we can access the first character. Each successive index contains the next character—so 1 is the second Char.
Example. This program written in the VB.NET language accesses some chars from a String. The String "abc" contains 3 characters.
Part 1 We get the first char by using an expression with the index 0. Chars (like arrays) are zero-indexes in VB.NET.
Array
Part 2 The second char is at the index 0. It is possible for any access that is out-of-range to throw an exception.
Part 3 The last char in a String of length 1 or more is located at the Length minus one. This won't work on an empty string.
Part 4 To avoid throwing exceptions by accessing a Char at an index, we can wrap the test inside an If-statement.
If
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 Module
FIRST: 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.
This page was last updated on Jun 19, 2024 (new).
Home
Changes
© 2007-2024 Sam Allen.