gpt4 book ai didi

c# - 如何制作锯齿状阵列?

转载 作者:太空宇宙 更新时间:2023-11-03 17:37:40 26 4
gpt4 key购买 nike

像一个简单的数组一样思考:

Console.WriteLine("Number: ");
int x = Convert.ToInt32(Console.ReadLine());

string[] strA = new string[x];

strA[0] = "Hello";
strA[1] = "World";

for(int i = 0;i < x;i++)
{
Console.WriteLine(strA[i]);
}

现在,我该如何使用双数组来实现?

我已经试过了:

Console.WriteLine("Number 1: ");
int x = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Number 2: ");
int y = Convert.ToInt32(Console.ReadLine());

// Got an error, right way string[x][];
// But how can I define the second array?
string[][] strA = new string[x][y];

strA[0][0] = "Hello";
strA[0][1] = "World";
strA[1][0] = "Thanks";
strA[1][1] = "Guys";

for(int i = 0;i < x;i++)
{
for(int j = 0;i < y;i++)
{
// How can I see the items?
Console.WriteLine(strA[i][j]);
}
}

如果有更简单的方法,我会很乐意学习。

仅供学习,我是第一次学习double array,请耐心等待:)

这是我的例子: https://dotnetfiddle.net/PQblXH

最佳答案

您正在使用锯齿状数组(即数组 string[][] 的数组),而不是2D 数组(字符串[,])

如果你想硬编码:

  string[][] strA = new string[][] { // array of array
new string[] {"Hello", "World"}, // 1st line
new string[] {"Thanks", "Guys"}, // 2nd line
};

如果您想提供xy:

  string[][] strA = Enumerable
.Range(0, y) // y lines
.Select(line => new string[x]) // each line - array of x items
.ToArray();

最后,如果我们想在不使用 Linq 的情况下初始化 strA 但所有 for 循环都很好(不像二维数组,锯齿状 数组可以包含不同长度的内部数组):

  // strA is array of size "y" os string arrays (i.e. we have "y" lines)
string[][] strA = new string[y][];

// each array within strA
for (int i = 0; i < y; ++i)
strA[i] = new string[x]; // is an array of size "x" (each line of "x" items)

编辑让我们逐行打印锯齿状数组:

很好的旧for 循环

  for (int i = 0; i < strA.Length; ++i) {
Console.WriteLine();

// please, note that each line can have its own length
string[] line = strA[i];

for (int j = 0; j < line.Length; ++j) {
Console.Write(line[j]); // or strA[i][j]
Console.Write(' '); // delimiter, let it be space
}
}

紧凑的代码:

  Console.Write(string.Join(Environment.newLine, strA
.Select(line => string.Join(" ", line))));

关于c# - 如何制作锯齿状阵列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55300957/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com