我想将一个字符串数组转换为单个字符串。
string[] test = new string[2];
test[0] = "Hello ";
test[1] = "World!";
我想要类似于“Hello World!”的东西。
string[] test = new string[2];
test[0] = "Hello ";
test[1] = "World!";
string.Join("", test);
使用Concat()方法比已经提到的Join()
方法稍微更快。它不需要像Join()
一样的空分隔符参数。例如:
string[] test = new string[2];
test[0] = "Hello ";
test[1] = "World!";
string result = String.Concat(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也可以用于提高性能,但代码会变得有点长。尝试:
String.Join("", test);
应该返回一个将两个元素拼接在一起的字符串。 ""
表示你想要这些字符串之间没有任何分隔符。// string[] test = new string[2];
// test[0] = "Hello ";
// test[1] = "World!";
string[] test = { "Hello", "World" }; // Alternative array creation syntax
string result = String.Join(" ", test);
Aggregate
也可以用于相同的目的。string[] test = new string[2];
test[0] = "Hello ";
test[1] = "World!";
string joinedString = test.Aggregate((prev, current) => prev + " " + current);
String.Join
,因为会构造多个额外的字符串。请阅读 https://dev59.com/h3VC5IYBdhLWcg3wrDJd 以获取正确的 Aggregate
变体。 - Alexei Levenkov string ConvertStringArrayToString(string[] array)
{
//
// Concatenate all the elements into a StringBuilder.
//
StringBuilder strinbuilder = new StringBuilder();
foreach (string value in array)
{
strinbuilder.Append(value);
strinbuilder.Append(' ');
}
return strinbuilder.ToString();
}
string.Join(" ", array)
(除了你的方法会在最后加上空格)。为什么不直接使用库中的方法呢? - davidg我使用了这种方法来加快我的项目:
RichTextBox rcbCatalyst = new RichTextBox()
{
Lines = arrayString
};
string text = rcbCatalyst.Text;
rcbCatalyst.Dispose();
return text;
RichTextBox.Text 会自动将数组转换为多行字符串!
像这样:
string str= test[0]+test[1];
你也可以使用循环:
for(int i=0; i<2; i++)
str += test[i];
var separator = ", ";
string.Join(separator , test);
- drpawelostring.Join(string.Empty, test)
而不是使用一个空括号。 - now he who must not be named.