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

2019-01-04 06:20发布

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.

7条回答
霸刀☆藐视天下
2楼-- · 2019-01-04 06:54
char[] chars = {'a', ' ', 's', 't', 'r', 'i', 'n', 'g'};
string s = new string(chars);
查看更多
We Are One
3楼-- · 2019-01-04 06:58

Another alternative

char[] c = { 'R', 'o', 'c', 'k', '-', '&', '-', 'R', 'o', 'l', 'l' };
string s = String.Concat( c );

Debug.Assert( s.Equals( "Rock-&-Roll" ) );
查看更多
劳资没心,怎么记你
4楼-- · 2019-01-04 07:08

Use the constructor of string which accepts a char[]

char[] c = ...;
string s = new string(c);
查看更多
不美不萌又怎样
5楼-- · 2019-01-04 07:11
char[] characters;
...
string s = new string(characters);
查看更多
Rolldiameter
6楼-- · 2019-01-04 07:18

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"
查看更多
不美不萌又怎样
7楼-- · 2019-01-04 07:18

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());
查看更多
登录 后发表回答