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.
There's a constructor for this:
char[] chars = {'a', ' ', 's', 't', 'r', 'i', 'n', 'g'};
string s = new string(chars);
Use the constructor of string which accepts a char[]
char[] c = ...;
string s = new string(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"
Another alternative
char[] c = { 'R', 'o', 'c', 'k', '-', '&', '-', 'R', 'o', 'l', 'l' };
string s = String.Concat( c );
Debug.Assert( s.Equals( "Rock-&-Roll" ) );
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());
String.Join(string separator, char[] charArray) concatenates the elements of a specified array or the members of a collection, using the specified separator between each element or member:
char[] c = { 'A', ' ', 'B', ' ', 'C', '&', 'D'};
string stringResult = string.Join("", c); //A B C&D