Convert Char[] to String and Vice Versa

Today I was asked a question on the forums to convert a char array to string and vice versa. Here’s the code to do so:

C#

static void Main(string[] args)
{
char[] cArr = { 'a', 'b', 'c', 'd', 'e', 'f'};
// Convert char[] to string
string str = new string(cArr);
Console.WriteLine("char[] to string: {0}", str);

// Convert string to char[]
Console.WriteLine("string to char[]");
char[] newArr = str.ToCharArray();
for (int i = 0; i < newArr.Length; i++)
Console.WriteLine(newArr[i]);
Console.ReadLine();
}

VB.NET

Sub Main(ByVal args() As String)
Dim cArr() As Char = { "a"c, "b"c, "c"c, "d"c, "e"c, "f"c}
' Convert char[] to string
Dim str As New String(cArr)
Console.WriteLine("char[] to string: {0}", str)

' Convert string to char[]
Console.WriteLine("string to char[]")
Dim newArr() As Char = str.ToCharArray()
For i As Integer = 0 To newArr.Length - 1
Console.WriteLine(newArr(i))
Next i
Console.ReadLine()
End Sub

OUTPUT

image






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: