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);
new string(null)
yields String.Empty
and not null
! If you want to keep null
, you can make an extension method static string ToStringSafe(this char[] buf) { return buf == null ? null : new string(buf); }
.
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"
string.Join<char>("_", chars)
instead of string.Join("_", chars)
Another alternative
char[] c = { 'R', 'o', 'c', 'k', '-', '&', '-', 'R', 'o', 'l', 'l' };
string s = String.Concat( c );
Debug.Assert( s.Equals( "Rock-&-Roll" ) );
String.Concat
is nice because it accepts IEnumerable<char>
as a parameter, so we don't have to call ToArray()
when using LINQ.
Commented
Sep 4, 2022 at 0:16
Use the string constructor which takes as arguments a Char array, the start position in the array, and the length of array. Syntax is given below:
string stringFromArray = new string(charArray, 0, charArray.Length);
char[] charArray = new char[5] { 'a', 'b', 'c', '\0', '\0' }; string charsAsString = new string(charArray, 0, 3); // only want part of array.
Commented
Apr 17, 2019 at 19:08
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