Posts Converting between String and Char arrays

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 FCL, 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.

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...

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.

Dim original As String = <FONT color=#000000>"Testing 1.2.3."</FONT>

<FONT color=#000000>Dim<FONT color=#000000> array As Char<FONT color=#000000>()</FONT><FONT color=#000000> </FONT>= CType<FONT color=#000000>(original, Char<FONT color=#000000>())</FONT></FONT></FONT></FONT>

<FONT color=#000000><FONT color=#000000><FONT color=#000000></FONT></FONT></FONT><FONT color=#000000><FONT color=#000000><FONT color=#000000> <P class=MsoNormal style="MARGIN: 0in 0in 0pt">Dim<FONT color=#000000> text </FONT>As String<FONT color=#000000> =</FONT> CStr<FONT color=#000000>(array)</FONT></FONT></FONT></FONT></P>

This post is licensed under CC BY 4.0 by the author.