.NET / C# - Convert char[] to string
C#.NetArraysStringCharC# Problem Overview
What is the proper way to turn a char[]
into a string?
The ToString()
method from an array of characters doesn't do the trick.
C# Solutions
Solution 1 - C#
There's a constructor for this:
char[] chars = {'a', ' ', 's', 't', 'r', 'i', 'n', 'g'};
string s = new string(chars);
Solution 2 - C#
Use the constructor of string which accepts a char[]
char[] c = ...;
string s = new string(c);
Solution 3 - C#
char[] characters;
...
string s = new string(characters);
Solution 4 - C#
One other way:
char[] chars = {'a', ' ', 's', 't', 'r', 'i', 'n', 'g'};
string s = string.Join("", chars);
//we get "a string"
// or for fun:
string s = string.Join("_", chars);
//we get "a_ _s_t_r_i_n_g"
Solution 5 - C#
String mystring = new String(mychararray);
Solution 6 - C#
Use the string constructor which accepts chararray as argument, start position and length of array. Syntax is given below:
string charToString = new string(CharArray, 0, CharArray.Count());
Solution 7 - C#
Another alternative
char[] c = { 'R', 'o', 'c', 'k', '-', '&', '-', 'R', 'o', 'l', 'l' };
string s = String.Concat( c );
Debug.Assert( s.Equals( "Rock-&-Roll" ) );