Char
arrayA Char
array stores characters together. In some VB.NET programs we need to use an array of characters instead of a String
.
With Char
arrays we employ certain spatial memory optimizations. This type is a useful construct. We can replace StringBuilder
usage.
This program declares and instantiates a char
array in 3 ways. Usually in programs, the shortest syntax form is best, as it reduces the amount of text to read.
Char()
syntax is used with an array initializer. This is also a short
syntax form.Module Module1 Sub Main() ' Version 1: use the initializer syntax. Dim array1() As Char = {"a", "b", "c"} ' Version 2: use the long syntax. Dim array2(2) As Char array2(0) = "a" array2(1) = "b" array2(2) = "c" ' Version 3: another syntax. Dim array3() As Char = New Char() {"a", "c", "c"} ' Display lengths. Console.WriteLine(array1.Length) Console.WriteLine(array2.Length) Console.WriteLine(array3.Length) End Sub End Module3 3 3
With a char
array, we can allocate the Char
buffer all at once, and then assign into each element. We do not need to resize the buffer.
StringBuilder
type and its Append
function.Module Module1 Sub Main() ' Allocate array of 100 characters. Dim array(100) As Char ' Fill array with a character. For index As Integer = 0 To 100 array(index) = "-" Next ' Write some characters. Console.WriteLine(array(0)) Console.WriteLine(array(100)) End Sub End Module- -
ToCharArray
The easiest way to get a char
array is probably ToCharArray
. We can specify a string
literal, and create an array from the characters with this function in just one line.
Module Module1 Sub Main() Dim value As String = "test" ' Get char array from string. Dim array() As Char = value.ToCharArray() ' Loop and print the chars. For Each element As Char In array Console.WriteLine("CHAR: {0}", element) Next End Sub End ModuleCHAR: t CHAR: e CHAR: s CHAR: t
How much faster is using a Char
array to build up a sequence of characters in memory than is using a StringBuilder
? This optimization can result in a 10X speedup.
A char
array is the ideal array type for building up character data. It conforms to the standard array syntax in VB.NET. It can help many programs.