向数组中添加数组

实现效果:

  

实现代码:

        static void Main(string[] args)
        {
            int index;
            Program pro = new Program();
            int[] arr_1 = pro.random_array(15);
            int[] arr_2 = pro.random_array(5);
            Console.WriteLine("生成的随机数组为:\n"+pro.loop_elements(arr_1));
            Console.WriteLine("进行插入的数组为:\n"+pro.loop_elements(arr_2));
            Console.WriteLine("输入要插入的位置:");
            int.TryParse(Console.ReadLine().ToString(),out index);
            Console.WriteLine("插入后的新数组为:\n"+pro.loop_elements(pro.add_array_inarray(arr_1,index,arr_2)));
        }
        //定义生成随机数组方法
        public int[] random_array(int leng_range) {
            int[] tempArray = new int[leng_range];
            for (int i = 0; i < tempArray.Length;i++ )
            {
                tempArray[i] = (new Random()).Next(1,20);
                System.Threading.Thread.Sleep(30);
            }
            return tempArray;
        }

        //定义遍历元素方法
        public string loop_elements(int[] int_arr) {
            string result="";
            foreach(int i in int_arr){
                result +=(i+" ");
            }
            return result;
        }

        //定义插入数组到数组方法
        public int[] add_array_inarray(int[] ArrayBorn,int Index,int[] ArrayValue) {
            if (Index > ArrayBorn.Length)
                Index = ArrayBorn.Length;
            int[] tempArray=new int[ArrayBorn.Length+ArrayValue.Length];
            int count=-1;
            for (int i = 0; i < tempArray.Length;i++ )
            {
                if (Index >= 0)
                {
                    if (i < Index)
                        tempArray[i] = ArrayBorn[i];
                    else if (i >= Index && i < (Index + ArrayValue.Length))
                    {
                        count++;
                        tempArray[i] = ArrayValue[count];                      
                    }
                    else
                        tempArray[i] = ArrayBorn[i - ArrayValue.Length];
                }
                else 
                {
                    if (i<ArrayValue.Length)
                    {
                        count++;
                        tempArray[i] = ArrayValue[count];
                    }
                    else
                        tempArray[i] = ArrayBorn[i - ArrayValue.Length];
                }
            } return tempArray;
        }

  

猜你喜欢

转载自www.cnblogs.com/feiyucha/p/10060185.html
今日推荐