Post

Converting between String and Char arrays

Someone asked me if I knew how to convert values between String and Char arrays… I remember needing to do that in the past and just gave up choosing to use Byte arrays instead (which for that purpose was fine).

First things first… when you normally think of text being displayed on the screen (let’s say in a TextBox), you think of each character in that string as being an ASCII value between 0-255. You would also think that a Char is going to represent on of those values and each value in a Char array taking up one 8-bit numeric value. In reality, a Char is a 16-bit value in order to handle the UniCode character table.

Within the BCL, you have the System.Text.AsciiEncoding and System.Text.UniCodeEncoding namespaces that will do a ton of work… but digging through those trying to “something easy” is not really all the straight forward.

So… looking for an easier answer I wanted to try something. I knew that the following existed and worked great.

1
Dim array As Char() = ("Testing 1.2.3.").ToCharArray

Basically, just creating a string value and converting it to a Char array using the ToCharArray of the String object. So, since the String object contains a method to convert to a Char array… surely it must have some mechanism to convert a Char array to a String. If your looking for a method… your not going to find one on the String object. Instead, it’s hiding in one of the overloaded constructors for a String. So…

1
Dim text As String = New String(array)

There you go, that’s the easiest way to convert a String to a Char array and back.

UPDATE: Thanks to Paul for bringing to my attention the language specific features for doing this. Here’s a code snippet to demonstrate the CStr() and CType() methods.

1
2
3
Dim original As String = "Testing 1.2.3."
Dim array As Char() = CType(original, Char())
Dim text As String = CStr(array)
This post is licensed under CC BY 4.0 by the author.