我想将一个字符串数组转换为单个字符串。
string[] test = new string[2];
test[0] = "Hello ";
test[1] = "World!";
我想要一些像“Hello World!”
我想将一个字符串数组转换为单个字符串。
string[] test = new string[2];
test[0] = "Hello ";
test[1] = "World!";
我想要一些像“Hello World!”
当前回答
在接受的答案中,字符串。Join并不是最佳实践。字符串。应该使用Concat,因为OP在第一项中包含了一个尾随空格:“Hello”(而不是使用空分隔符)。
然而,由于OP请求的结果是"Hello World!", String。Join仍然是合适的方法,但是后面的空格应该移动到分隔符。
// string[] test = new string[2];
// test[0] = "Hello ";
// test[1] = "World!";
string[] test = { "Hello", "World" }; // Alternative array creation syntax
string result = String.Join(" ", test);
其他回答
聚合也可以用于相同的。
string[] test = new string[2];
test[0] = "Hello ";
test[1] = "World!";
string joinedString = test.Aggregate((prev, current) => prev + " " + current);
我用这种方法让我的项目更快:
RichTextBox rcbCatalyst = new RichTextBox()
{
Lines = arrayString
};
string text = rcbCatalyst.Text;
rcbCatalyst.Dispose();
return text;
RichTextBox。文本将自动将您的数组转换为多行字符串!
string[] test = new string[2];
test[0] = "Hello ";
test[1] = "World!";
string.Join("", test);
Try:
String.Join("", test);
它应该返回一个将两个元素连接在一起的字符串。""表示您希望将字符串连接在一起而不使用任何分隔符。
你所需要的就是一个简单的string.Concat()。
string[] test = new string[2];
test[0] = "Hello ";
test[1] = "World!";
string result = string.Concat(test);
如果你还需要添加分隔符(空格,逗号等),那么应该使用string.Join()。
string[] test = new string[2];
test[0] = "Red";
test[1] = "Blue";
string result = string.Join(",", test);
如果必须在包含数百个元素的字符串数组上执行此操作,那么从性能角度来看,string. join()更好。只需要给出一个“”(空白)参数作为分隔符。为了提高性能,也可以使用StringBuilder,但它会使代码变长。