.NET / C# - Convert char[] to string

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.

0

7 Answers

There's a constructor for this:

char[] chars = {'a', ' ', 's', 't', 'r', 'i', 'n', 'g'};
string s = new string(chars);
3

Use the constructor of string which accepts a char[]

char[] c = ...;
string s = new string(c);
2
char[] characters;
...
string s = new string(characters);

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"
5
String mystring = new String(mychararray);

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());
2

Another alternative

char[] c = { 'R', 'o', 'c', 'k', '-', '&', '-', 'R', 'o', 'l', 'l' };
string s = String.Concat( c );
Debug.Assert( s.Equals( "Rock-&-Roll" ) );
0

You Might Also Like