2011-12-10 94 views
2
  1. 我試圖從相鄰行和列中的二維數組中打印四個數字。在陣列中輸入的數字分別爲:顯示數組元素

    404 414 424 434 444 
        505 506 507 508 509 
        312 313 314 315 316 
        822 823 824 825 826 
    
  2. 我想要的

    row1,col2; row1,col3 
        row2,col2; row2,col3 
    
  3. 輸出我有顯示是

    507508 
        314315 
    
  4. 我想顯示爲

    507 508 
        314 315 
    
  5. ,我已寫入的顯示代碼是:

    Console. Write Line("Values =>" +array[row,col] +array[row,col1]); 
    
        Console. Write Line("Values =>" +array[row1,col] +array[row1,col1] ); 
    
  6. 我試圖把雙&符號,雙引號來增加+陣列[行,列和±陣列之間的空間[行中,col1]以獲得顯示我想要的。我同樣對待代碼的下一行。雙連字符和雙引號不會改變顯示;它仍然如上文第3段所示,兩者都有變化。

&。如何獲得第4段所示的顯示?請幫助。

回答

2

好,加入一個空格:

Console.WriteLine("Values =>" +array[row1,col] + " " + array[row1,col1] ); 
+0

謝謝,它工作。我在雙引號前錯過了+符號。上帝保佑你..再次感謝..... Rajdhan上校 – user1091120

2

嘗試

Console.WriteLine("Values => {0} {1}", array[row,col], array[row,col1]); 
+0

謝謝,它工作。我對這種做法並不是很熟悉。上帝保佑你......再次感謝..... Rajdhan上校 - – user1091120

4

當你這樣做:

"Values =>" +array[row,col] +array[row,col1] 

你串接陣列單元格的值直接在一起,而不任何空間。

你需要在它們之間加空格:

"Values =>" + array[row,col] + " " + array[row,col1] 

一個更好的辦法是使用format strings,那裏的空間嵌入在格式化字符串:

Console.WriteLine("Values => {0} {1}", array[row,col], array[row,col1]); 
+0

非常感謝主席先生。我曾試過這雙雙引號,但沒有在雙引號前加上+號。這正是我想要做的!再次感謝。 – user1091120

0

您可以使用字符串。加入如下:

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)); 
}