C#在既有数组中插入另一个数组:Array.Copy方法 vs 自定义插入方法

目录

一、使用的方法

1.使用Array.Copy方法

[2.Copy(Array, Int32, Array, Int32, Int32)](#2.Copy(Array, Int32, Array, Int32, Int32))

[3. 使用自定义的方法](#3. 使用自定义的方法)

二、实例

1.示例1:使用Array.Copy方法

2.示例2:使用自定义的方法


一、使用的方法

1.使用Array.Copy方法

首先定义了一个名为InsertArray的函数,它接受三个参数:一个原始数组originalArray,一个索引index和一个要插入的数组arrayToInsert。我们首先计算新数组的大小,然后创建一个新的数组newArray。接下来,我们使用Array.Copy方法将原始数组的一部分复制到新数组中,然后将要插入的数组复制到新数组中的指定索引位置。最后,我们再次使用Array.Copy方法将原始数组的剩余部分复制到新数组中。最后,我们使用foreach循环遍历新数组并输出每个元素。

这个方法会修改原始数组。如果您不希望修改原始数组,可以在方法开始时创建原始数组的副本。

2.Copy(Array, Int32, Array, Int32, Int32)

复制 Array 中的一系列元素(从指定的源索引开始),并将它们粘贴到另一 Array 中(从指定的目标索引开始)。 长度和索引指定为 32 位整数。

cs 复制代码
public static void Copy (Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length);

参数
sourceArray    Array
包含要复制的数据的 Array。

sourceIndex    Int32
一个 32 位整数,它表示 sourceArray 中复制开始处的索引。

destinationArray    Array
接收数据的 Array。

destinationIndex    Int32
一个 32 位整数,它表示 destinationArray 中存储开始处的索引。

length    Int32
一个 32 位整数,它表示要复制的元素数目。

例外
ArgumentNullException
sourceArray 上声明的默认值为 null。
或
destinationArray 为 null。

RankException
sourceArray 和 destinationArray 具有不同的秩。

ArrayTypeMismatchException
sourceArray 和 destinationArray 属于不兼容的类型。

InvalidCastException
sourceArray 中至少有一个元素无法转换为 destinationArray 的类型。

ArgumentOutOfRangeException
sourceIndex 少于 sourceArray 的第一个维度的下限。
- 或 -
destinationIndex 少于 destinationArray 的第一个维度的下限。
- 或 -
length 小于零。

ArgumentException
length 大于从 sourceIndex 到 sourceArray 末尾的元素数。
- 或 -
length 大于从 destinationIndex 到 destinationArray 末尾的元素数。

3. 使用自定义的方法

首先需要定义两个一维数组,分别用来作为原始数组和要插入的数组,然后修改原始数组的长度(这里使用Length属性分别获取原始数组和要插入数组的长度,然后把获得的长度相加,作为新数组的长度),从而在其中增加一个数组。

二、实例

1.示例1:使用Array.Copy方法

cs 复制代码
// 要将一个数组插入到另一个数组的指定索引位置,可以使用以下方法:

namespace _096_1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            ArgumentNullException.ThrowIfNull(args);
            int[] originalArray = [1, 2, 3, 4, 5];
            int index = 2;
            int[] arrayToInsert = [7,8,9];
            InsertArray(originalArray, index, arrayToInsert);
            Console.WriteLine();
        }
        /// <summary>
        /// 向数组中插入数组的方法
        /// </summary>
        /// <param name="originalArray">源数组</param>
        /// <param name="index">要出入的索引位置</param>
        /// <param name="arrayToInsert">要插入的数组</param>
        public static void InsertArray(int[] originalArray, int index, int[] arrayToInsert)
        {
            int newSize = originalArray.Length + arrayToInsert.Length;
            int[] newArray = new int[newSize];

            Array.Copy(originalArray, 0, newArray, 0, index);
            Array.Copy(arrayToInsert, 0, newArray, index, arrayToInsert.Length);
            Array.Copy(originalArray, index, newArray, index + arrayToInsert.Length, originalArray.Length - index);

            foreach (int item in newArray)
            {
                Console.Write(item + " ");
            }
        }
    }
}
//运行结果:
/*
1 2 7 8 9 3 4 5

 */

2.示例2:使用自定义的方法

cs 复制代码
// 在数组中添加另一个数组
namespace _096
{
    public partial class Form1 : Form
    {
        private Label? label1;
        private Label? label2;
        private Label? label3;
        private TextBox? textBox1;
        private TextBox? textBox2;
        private TextBox? textBox3;
        private Button? button1;
        private RichTextBox? richTextBox1;
        private Label? label4;
        private int[] int_array1 = new int[8];//定义数组类型变量
        private int[] int_array2 = new int[4];//定义数组类型变量

        public Form1()
        {
            InitializeComponent();
            StartPosition = FormStartPosition.CenterScreen;
            Load += Form1_Load;
        }

        private void Form1_Load(object? sender, EventArgs e)
        {
            // 
            // label1
            // 
            label1 = new Label
            {
                AutoSize = true,
                Location = new Point(12, 9),
                Name = "label1",
                Size = new Size(56, 17),
                TabIndex = 0,
                Text = "源数组:"
            };
            label1.Click += Label1_Click;
            // 
            // label2
            // 
            label2 = new Label
            {
                AutoSize = true,
                Location = new Point(12, 38),
                Name = "label2",
                Size = new Size(80, 17),
                TabIndex = 1,
                Text = "插入的数组:"
            };
            label2.Click += Label2_Click;
            // 
            // label3
            // 
            label3 = new Label
            {
                AutoSize = true,
                Location = new Point(196, 38),
                Name = "label3",
                Size = new Size(44, 17),
                TabIndex = 2,
                Text = "索引:"
            };
            // 
            // textBox1
            // 
            textBox1 = new TextBox
            {
                Location = new Point(97, 3),
                Name = "textBox1",
                Size = new Size(230, 23),
                TabIndex = 3
            };
            // 
            // textBox2
            // 
            textBox2 = new TextBox
            {
                Location = new Point(94, 32),
                Name = "textBox2",
                Size = new Size(100, 23),
                TabIndex = 4
            };
            // 
            // textBox3
            // 
            textBox3 = new TextBox
            {
                Location = new Point(242, 32),
                Name = "textBox3",
                Size = new Size(40, 23),
                TabIndex = 5
            };
            // 
            // button1
            // 
            button1 = new Button
            {
                Location = new Point(286, 32),
                Name = "button1",
                Size = new Size(41, 23),
                TabIndex = 6,
                Text = "插入",
                UseVisualStyleBackColor = true
            };
            button1.Click += Button1_Click;
            // 
            // richTextBox1
            // 
            richTextBox1 = new RichTextBox
            {
                Location = new Point(12, 88),
                Name = "richTextBox1",
                Size = new Size(315, 46),
                TabIndex = 7,
                Text = ""
            };
            // 
            // label4
            // 
            label4 = new Label
            {
                AutoSize = true,
                Location = new Point(12, 67),
                Name = "label4",
                Size = new Size(56, 17),
                TabIndex = 8,
                Text = "新数组:"
            };
            // 
            // Form1
            // 
            AutoScaleDimensions = new SizeF(7F, 17F);
            AutoScaleMode = AutoScaleMode.Font;
            ClientSize = new Size(339, 146);
            Controls.Add(label4);
            Controls.Add(richTextBox1);
            Controls.Add(button1);
            Controls.Add(textBox3);
            Controls.Add(textBox2);
            Controls.Add(textBox1);
            Controls.Add(label3);
            Controls.Add(label2);
            Controls.Add(label1);
            Name = "Form1";
            Text = "向数组中插入另一个数组";
        }
        /// <summary>
        /// 生成源数组
        /// </summary>
        private void Label1_Click(object? sender, EventArgs e)
        {
            textBox1!.Clear();
            for (int i = 0; i < int_array1.GetUpperBound(0) + 1; i++)
            {
                int_array1[i] = i;
            }
            for (int i = 0; i < int_array1.GetUpperBound(0) + 1; i++)
            {
                textBox1.Text += int_array1[i] + " ";
            }
        }
        /// <summary>
        /// 生成要插入的数组
        /// </summary>
        private void Label2_Click(object? sender, EventArgs e)
        {
            textBox2!.Clear();
            for (int i = 0; i <= int_array2.GetUpperBound(0); i++)
            {
                int_array2[i] = i+3;
            }
            for (int i = 0; i <= int_array2.GetUpperBound(0); i++)
            {
                textBox2!.Text += int_array2[i] + " ";
            }
        }
        /// <summary>
        /// 执行插入事件,调用插入方法
        /// </summary>
        private void Button1_Click(object? sender, EventArgs e)
        {
            richTextBox1!.Clear();
            if ((textBox1!.Text != "") && (textBox2!.Text != "") && (textBox3!.Text != ""))
            {
                int_array1 = AddArray(int_array1, int_array2, Convert.ToInt32(textBox3!.Text));

                for (int i = 0; i < int_array1.GetUpperBound(0) + 1; i++)
                {
                    richTextBox1.Text += int_array1[i] + " ";
                }
            }
            else
            {
                MessageBox.Show("输入的信息不能为空", "提示");
            }  
        }
       
        /// <summary>
        /// 向一维数组中添加一个数组
        /// </summary>
        /// <param name="ArrayBorn">源数组</param>
        /// <param name="ArrayAdd">要添加的数组</param>
        /// <param name="Index">添加索引</param>
        /// <returns>新得到的数组</returns>
        static int[] AddArray(int[] ArrayBorn, int[] ArrayAdd, int Index)
        {
            if (Index >= ArrayBorn.Length)
                Index = ArrayBorn.Length - 1;
            int[] TemArray = new int[ArrayBorn.Length + ArrayAdd.Length];//声明一个新的数组
            for (int i = 0; i < TemArray.Length; i++)
            {
                if (Index >= 0)
                {
                    if (i < (Index /*+ 1*/))//在索引位置插入,注释掉的:在索引的下一个位置插入
                        TemArray[i] = ArrayBorn[i];//交换元素值
                    else if (i == (Index /*+ 1*/))
                    {
                        for (int j = 0; j < ArrayAdd.Length; j++)
                            TemArray[i + j] = ArrayAdd[j];
                        i = i + ArrayAdd.Length - 1;
                    }
                    else
                        TemArray[i] = ArrayBorn[i - ArrayAdd.Length];
                }
                else
                {
                    if (i == 0)//判断遍历到的索引是否为0
                    {
                        for (int j = 0; j < ArrayAdd.Length; j++)
                            TemArray[i + j] = ArrayAdd[j];
                        i = i + ArrayAdd.Length - 1;
                    }
                    else
                        TemArray[i] = ArrayBorn[i - ArrayAdd.Length];
                }
            }
            return TemArray;
        }
   
    }
}

相关推荐
沐浴露z1 小时前
【JVM】详解 垃圾回收
java·jvm·算法
代码欢乐豆1 小时前
编译原理机测客观题(7)优化和代码生成练习题
数据结构·算法·编译原理
祁同伟.2 小时前
【C++】二叉搜索树(图码详解)
开发语言·数据结构·c++·容器·stl
Scc_hy2 小时前
强化学习_Paper_2000_Eligibility Traces for Off-Policy Policy Evaluation
人工智能·深度学习·算法·强化学习·rl
Joy T2 小时前
Solidity智能合约存储与数据结构精要
数据结构·区块链·密码学·智能合约·solidity·合约function
leke20033 小时前
2025年10月17日
算法
CoovallyAIHub3 小时前
Mamba-3震撼登场!Transformer最强挑战者再进化,已进入ICLR 2026盲审
深度学习·算法·计算机视觉
海绵宝宝的好伙伴3 小时前
【数据结构】哈希表的理论与实现
数据结构·哈希算法·散列表
Aqua Cheng.3 小时前
代码随想录第七天|哈希表part02--454.四数相加II、383. 赎金信、15. 三数之和、18. 四数之和
java·数据结构·算法·散列表
zym大哥大3 小时前
哈希表封装myunordered_map以及set
数据结构·散列表