.NET/C# - 将char []转换为字符串

Bud*_*Joe 388 .net c# arrays string char

将a char[]变为字符串的正确方法是什么?

ToString()来自字符数组的方法不起作用.

Joe*_*orn 649

char[] chars = {'a', ' ', 's', 't', 'r', 'i', 'n', 'g'};
string s = new string(chars);
Run Code Online (Sandbox Code Playgroud)

  • 注意`new string(null)`产生`String.Empty`而**不产生**`null`!如果你想保持`null`,你可以创建一个扩展方法`static string ToStringSafe(this char [] buf){return buf == null?null:new string(buf); }`. (11认同)
  • @Skod:看到"新"表达式不可能返回除对象实例之外的值,这对任何人来说都不应该是一个惊喜. (6认同)
  • @MattiVirkkunen:抛出异常也是合理的做法。这就是我猜测将 null 传递给字符串构造函数时的行为。 (2认同)

Jar*_*Par 79

使用接受char []的string的构造函数

char[] c = ...;
string s = new string(c);
Run Code Online (Sandbox Code Playgroud)

  • 如果只有你快3分钟,你会在提出问题之前回答! (53认同)
  • 忘记分钟。只需17秒。上面我的答案是我在网站上投票率第二高的答案。事实上,我现在在这里是因为有人再次投票,差不多 10 年后。这两个答案并没有什么不同……但我的发布速度快了 17 秒,这意味着 500 票的差异:/ (3认同)

Aus*_*nen 35

char[] characters;
...
string s = new string(characters);
Run Code Online (Sandbox Code Playgroud)


Sem*_*nko 28

另一种方式:

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"
Run Code Online (Sandbox Code Playgroud)

  • 编译器自动执行此操作,因为在编译时已知chars类型。 (2认同)

Sha*_*and 20

String mystring = new String(mychararray);
Run Code Online (Sandbox Code Playgroud)


Dil*_*are 14

使用接受chararray作为参数,起始位置和数组长度的字符串构造函数.语法如下:

string charToString = new string(CharArray, 0, CharArray.Count());
Run Code Online (Sandbox Code Playgroud)


Mic*_*l J 11

另一种选择

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

Debug.Assert( s.Equals( "Rock-&-Roll" ) );
Run Code Online (Sandbox Code Playgroud)

  • `String.Concat` 很好,因为它接受 `IEnumerable<char>` 作为参数,因此我们在使用 LINQ 时不必调用 `ToArray()`。 (3认同)