System.Array 提供豐富靜態方法操作一維/多維陣列。本文深入解析 清空、查找、排序/反轉 三大核心方法,並附綜合練習題強化陣列思維。
int[] arr = {1,2,3,4,5};
Array.Clear(arr, 1, 2); // 索引 1 起,清除 2 個元素
// 結果:1, 0, 0, 4, 5 (Length 仍為 5)
⚠️ **關鍵觀念**:陣列長度不可變,Clear 僅將目標區段設為型別預設值(數值 0、參考 null、布林 false)。
| 方法簽名 | 行為 |
|---|---|
IndexOf(Array, value) | 從索引 0 向後找第一個相符項 |
IndexOf(Array, value, startIndex) | 從 startIndex 向後找 |
IndexOf(Array, value, startIndex, count) | 從 startIndex 起,檢查 count 個元素 |
LastIndexOf(...) | 對稱:從尾端向前找 |
int[] arr = {3,2,1,5,2,4};
Console.WriteLine(Array.IndexOf(arr, 2)); // 1
Console.WriteLine(Array.LastIndexOf(arr, 2)); // 4
Console.WriteLine(Array.IndexOf(arr, 2, 2, 3)); // 4 (索引 2 起找 3 個:1,5,2)
string path = @"C:\Upload\photo.jpg";
int dot = path.LastIndexOf('.'); // 找最後一個 '.'
string ext = path.Substring(dot + 1); // "jpg"
if (new[] {"jpg","png","gif"}.Contains(ext)) { /* 合法圖片 */ }
| 方法 | 說明 |
|---|---|
Sort(Array) | 一維陣列預設遞增 (QuickSort) |
Sort(Array, index, length) | 部分區段排序 |
Sort(Array, IComparer) | 自訂比較器 |
Reverse(Array) | 整體反轉順序 |
Reverse(Array, index, length) | 部分反轉 |
int[] a = {3,1,5,4,2};
Array.Reverse(a); // 2,4,5,1,3
Array.Sort(a); // 1,2,3,4,5
Array.Reverse(a, 2, 2); // 1,2,4,3,5 (索引 2,3 反轉)
Array.Sort(a, 2, 2); // 1,2,3,4,5 (索引 2,3 排序)
char[] chars = {'A','B','C','D','E'};
Console.WriteLine(new string(chars)); // 最簡潔
// 或
foreach(char c in chars) Console.Write(c);
int[,] matrix = { {2,4,6}, {8,10,11}, {12,14,16} };
for (int r = 0; r < matrix.GetLength(0); r++)
{
for (int c = 0; c < matrix.GetLength(1); c++)
Console.Write($"{matrix[r,c]:D2} ");
Console.WriteLine();
}
// 輸出:
// 02 04 06
// 08 10 11
// 12 14 16
int[,] scores = new int[3, 3]; // [學生, 0:座號 1:國文 2:數學]
for (int i = 0; i < 3; i++)
{
Console.Write($"第 {i+1} 位學號:"); scores[i,0] = int.Parse(Console.ReadLine());
Console.Write("國文:"); scores[i,1] = int.Parse(Console.ReadLine());
Console.Write("數學:"); scores[i,2] = int.Parse(Console.ReadLine());
}
bool hasFail = false;
for (int i = 0; i < 3; i++)
{
Console.WriteLine($"座號:{scores[i,0]} 國文:{scores[i,1]} 數學:{scores[i,2]}");
if (scores[i,1] < 60) { Console.WriteLine($"國文不及格座號:{scores[i,0]}"); hasFail = true; }
}
if (!hasFail) Console.WriteLine("國文全班及格!");
缺點提示:座號可重複、程式碼較冗長。下一單元 Hashtable 可優雅解決鍵唯一與 O(1) 查找問題。
new int[5]、new int[] {1,2}、new int[,] {{1,2},{3,4}}、交錯陣列 new int[3][]0 ~ Length-1,越界拋 IndexOutOfRangeExceptionint[] b = a; 兩變數指向同一陣列,修改互影響foreach 唯讀遍歷,不可修改元素GetLength(維度) 取得各維長度Array.Sort/Reverse/Clear/IndexOf 熟練運用