Convert Char Array to String
This page was last reviewed on Nov 9, 2023.
Dot Net Perls
Char Array, String. In VB.NET a Char array can be converted into a regular String. With the String instance constructor we perform this conversion.
Function info. Char arrays can be readily converted into String instances in VB.NET. We do not need to build up a string character-by-character unless we must test characters first.
Char Array
Example. This program declares and assigns into a character array. Next, we invoke the String constructor, and pass the identifier of the character array reference in the argument slot.
Result The String constructor returns a new string. We assign a reference variable to it.
Detail The character array was assembled into a complete string, which can be used throughout your program.
Module Module1 Sub Main() ' Create a Char array using assignment syntax. Dim arr(8) As Char arr(0) = "T" arr(1) = "h" arr(2) = "a" arr(3) = "n" arr(4) = "k" arr(5) = " " arr(6) = "y" arr(7) = "o" arr(8) = "u" ' Create a String from the Char array. Dim value As String = New String(arr) ' Test. Console.WriteLine(value = "Thank you") End Sub End Module
In my experience, this approach to String construction is often the fastest. Another efficient way is to use a lookup table and avoid creating a new String in the first place.
String Constructor
Discussion. In VB.NET programs, methods often require a String argument. But in custom methods, you can change these to accept a Char() array. Then no Strings are needed. This reduces allocations.
Detail Performance improves. Allocating objects like strings is usually slower than reusing a single array.
Summary. Character arrays can be easily converted into String instances. Using this approach to creating certain kinds of character data can improve performance.
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 Nov 9, 2023 (edit).
© 2007-2024 Sam Allen.