.NET / C# - 将 char[] 转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1324009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
.NET / C# - Convert char[] to string
提问by BuddyJoe
What is the proper way to turn a char[]
into a string?
将 achar[]
变成字符串的正确方法是什么?
The ToString()
method from an array of characters doesn't do the trick.
ToString()
来自字符数组的方法不起作用。
采纳答案by Joel Coehoorn
char[] chars = {'a', ' ', 's', 't', 'r', 'i', 'n', 'g'};
string s = new string(chars);
回答by JaredPar
Use the constructor of string which accepts a char[]
使用接受 char[] 的 string 构造函数
char[] c = ...;
string s = new string(c);
回答by Austin Salonen
char[] characters;
...
string s = new string(characters);
回答by Shaun Rowland
String mystring = new String(mychararray);
回答by Semen Miroshnichenko
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"
回答by Dilip Nannaware
Use the string constructor which accepts chararray as argument, start position and length of array. Syntax is given below:
使用接受 chararray 作为参数、起始位置和数组长度的字符串构造函数。语法如下:
string charToString = new string(CharArray, 0, CharArray.Count());
回答by Michael J
Another alternative
另一种选择
char[] c = { 'R', 'o', 'c', 'k', '-', '&', '-', 'R', 'o', 'l', 'l' };
string s = String.Concat( c );
Debug.Assert( s.Equals( "Rock-&-Roll" ) );