标签:执行 == code 需要 数组 元素 main 循环 val
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="value">添加数组</param> 13 /// <returns></returns> 14 static int[] AddNewArray(int[] arrayBorn,int index,int[] arrayAdd) 15 { 16 if (index >= arrayBorn.Length) //第一种情况:索引大于等于数组最大长度 17 { 18 index = arrayBorn.Length; 19 } 20 int[] arrayNew = new int[arrayBorn.Length + arrayAdd.Length]; //声明一个新数组,长度为源数组+1 21 for (int i = 0;i < arrayNew.Length;i++) 22 { 23 if (index >= 0) 24 { 25 if (i < index) 26 { 27 arrayNew[i] = arrayBorn[i]; 28 } 29 else if (i == index) 30 { 31 for (int j = 0; j < arrayAdd.Length; j++) 32 { 33 arrayNew[i + j] = arrayAdd[j]; 34 } 35 i = i + arrayAdd.Length - 1; //注意:此时的索引需要减1,因为执行完此语句进入下次循环,i又会加1 36 } 37 else 38 { 39 arrayNew[i] = arrayBorn[i - arrayAdd.Length]; 40 } 41 } 42 else //第二种情况:索引小于0,一律视为等于0处理 43 { 44 if (i == 0) 45 { 46 for (int j = 0; j < arrayAdd.Length; j++) 47 { 48 arrayNew[i + j] = arrayAdd[j]; 49 } 50 i = i + arrayAdd.Length; 51 } 52 else 53 { 54 arrayNew[i] = arrayBorn[i - arrayAdd.Length]; 55 } 56 } 57 } 58 return arrayNew; 59 } 60 static void Main(string[] args) 61 { 62 int[] arrayInt = new int[] { 0,1,2,3,4,5,6,7,8,9}; 63 int[] arrayInt1 = new int[] { 4,3,2,1}; 64 Console.WriteLine("原数组元素:"); 65 foreach (int i in arrayInt) 66 { 67 Console.Write(i + " "); 68 } 69 Console.WriteLine(); 70 Console.WriteLine("要插入的数组:"); 71 foreach (int i in arrayInt1) 72 { 73 Console.Write(i + " "); 74 } 75 Console.WriteLine(); 76 arrayInt = AddNewArray(arrayInt,1, arrayInt1); 77 Console.WriteLine("插入新元素的数组"); 78 foreach (int i in arrayInt) 79 { 80 Console.Write(i + " "); 81 } 82 } 83 } 84 }
标签:执行 == code 需要 数组 元素 main 循环 val
原文地址:https://www.cnblogs.com/kyuusan/p/13022902.html