January 15, 2010

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



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

0 Responses to "Convert Char[] to String and Vice Versa"
 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions