1 using System; 2 3 namespace ConsoleApp1 4 { 5 class Program 6 { 7 /// <summary> 8 /// 刪除數組元素 9 /// </summary> 10 /// <param name="arrayBorn">源數組</param> 11 /// <param name="index">索引</param> 12 /// <param name="Len">刪除長度</param> 13 static string[] DeleteEle(string[] arrayBorn,int index,int Len) 14 { 15 if (Len < 0) //刪除長度小於0,返回 16 { 17 return arrayBorn; 18 } 19 if ( (index + Len) > arrayBorn.Length) //刪除長度超出數組范圍 20 { 21 Len = arrayBorn.Length - index; //將長度設置為能刪除的最大長度 22 } 23 for (int i = 0;i < arrayBorn.Length - ( index + Len); i++) //將刪除元素后面的元素往前移動 24 { 25 if ((index + i + Len) > arrayBorn.Length) //若刪除元素+刪除長度超過數組的范圍,即無法從數組中找到移動元素,則用null替代 26 { 27 arrayBorn[index + i] = null; 28 } 29 else //若能用數組的元素替換則用數組中的元素 30 { 31 arrayBorn[index + i] = arrayBorn[index + i + Len]; 32 } 33 } 34 /*不改變數組長度*/ 35 for (int j =Len;j > 0; j--) //將刪除元素后多余的元素置為null值 36 { 37 arrayBorn[arrayBorn.Length - j ] = null; 38 } 39 return arrayBorn; 40 /*改變數組長度 41 string[] newArray = new string[arrayBorn.Length-Len]; 42 for (int j =0;j < newArray.Length;j++) 43 { 44 newArray[j] = arrayBorn[j]; 45 } 46 return newArray; 47 */ 48 } 49 static void Main(string[] args) 50 { 51 string[] arrayString = new string[] { "0","1","2","3","4","5"}; 52 Console.WriteLine("原數組元素:"); 53 foreach (string i in arrayString) 54 { 55 Console.Write(i + " "); 56 } 57 Console.WriteLine(); 58 arrayString = DeleteEle(arrayString, 1, 3); 59 Console.WriteLine("刪除元素后的數組"); 60 foreach (String i in arrayString) 61 { 62 Console.Write(i + " "); 63 } 64 } 65 } 66 }