显示数组的元素
本文关键字:元素 数组 显示 | 更新日期: 2023-09-27 18:17:38
-
我试图从相邻行和列中的二维数组中打印四个数字。在数组中输入的数字为:
404 414 424 434 444 505 506 507 508 509 312 313 314 315 316 822 823 824 825 826
-
我想要输出
row1,col2; row1,col3 row2,col2; row2,col3
-
我得到的显示器是
507508 314315
-
我希望显示为
507 508 314 315
-
我编写的显示代码是:
Console. Write Line("Values =>" +array[row,col] +array[row,col1] ); Console. Write Line("Values =>" +array[row1,col] +array[row1,col1] );
-
我尝试放置双与号,双引号以增加+array[row,col]和+array[row,col1]之间的空格,以获得我想要的显示。我也以类似的方式处理了代码的下一行。双与号和双引号不会改变显示;它仍然如上文第3段所示,但有两项修改。
&.如何获得第 4 段所示的显示屏?请帮忙。
当你这样做时:
"Values =>" +array[row,col] +array[row,col1]
您将数组单元格的值直接连接在一起,没有任何空格。
您需要在它们之间添加一个空格:
"Values =>" + array[row,col] + " " + array[row,col1]
更好的方法是使用格式字符串,其中空格嵌入在格式字符串中:
Console.WriteLine("Values => {0} {1}", array[row,col], array[row,col1]);
好吧,通过添加一个空格:
Console.WriteLine("Values =>" +array[row1,col] + " " + array[row1,col1] );
试试
Console.WriteLine("Values => {0} {1}", array[row,col], array[row,col1]);
您可以使用字符串。按如下方式加入:
Console.WriteLine(string.Join(" ", array[row, col], array[row, col]));
添加更多数组元素更容易。
但是,使用交错数组会更有效(如果可能的话(。相同的任务更简单,允许您使用行范围和列范围。检查草稿示例。
// your array as jagged array
int[][] jtest = {
new int[] { 404, 414, 424, 434, 444 },
new int[] { 505, 506, 507, 508, 509 },
new int[] { 312, 313, 314, 315, 316 },
new int[] { 822, 823, 824, 825, 826 }
};
// definitions for row ranges
int firstRow = 1; int lastRow = 2;
// definitions for col ranges
int firstCol = 2; int lastCol = 3;
// int array for copying row elements in col range
int[] dump = new int[lastCol - firstCol + 1];
// do it
for (var i = firstRow; i <= lastRow; i++)
{
Array.Copy(jtest[i], firstCol, dump, 0, dump.Length);
Console.WriteLine(string.Join(" ", dump));
}