我已经尝试过stringbuilder,但它将合并列
// I have this array
{ { 1, 2 }, { 3, 4 }, { 5, 6 } };
//I want to convert it to a string
1 2
3 4
5 6
// with string builder
var output = new string[a.GetUpperBound(0) + 1];
for (int i = 0; i <= a.GetUpperBound(0); i++)
{
var sb = new StringBuilder();
for (int j = 0; j <= a.GetUpperBound(1); j++)
sb.Append(a[i, j]);
output[i] = sb.ToString();
}
the results will be
12
34
56
我发现了许多转换单个数组的方法,但找不到多维数组的方法
如果您想要简单的解决方案,请从2D阵列切换到锯齿状的阵列:
int[][] array = new int[][] {
new int[] { 1, 2, },
new int[] { 3, 4, },
new int[] { 5, 6, },
};
这样做后,您可以像这样简单
string result = String.Join(Environment.NewLine,
array.Select(items => String.Join(" ", items)));
// 1 2
// 3 4
// 5 6
Console.Write(result);
如果是2D数组,则必须实现以下内容:
int[,] array = new int[,] {
{ 1, 2, },
{ 3, 4, },
{ 5, 6, },
};
StringBuilder sb = new StringBuilder();
for (int i = 0; i < array.GetLength(0); ++i) {
if (i > 0)
sb.AppendLine();
for (int j = 0; j < array.GetLength(1); ++j) {
if (j > 0)
sb.Append(" ");
sb.Append(array[i, j]);
}
}
String result = sb.ToString();
// 1 2
// 3 4
// 5 6
Console.Write(result);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句