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



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) 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 is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: