【发布时间】:2010-10-18 12:12:27
【问题描述】:
如何将一个数组的一部分复制到另一个数组?
想想我有
int[] a = {1,2,3,4,5};
现在,如果我给出数组 a 的开始索引和结束索引,它应该被复制到另一个数组。
如果我将起始索引设为 1,将结束索引设为 3,则元素 2、3、4 应该被复制到新数组中。
【问题讨论】:
如何将一个数组的一部分复制到另一个数组?
想想我有
int[] a = {1,2,3,4,5};
现在,如果我给出数组 a 的开始索引和结束索引,它应该被复制到另一个数组。
如果我将起始索引设为 1,将结束索引设为 3,则元素 2、3、4 应该被复制到新数组中。
【问题讨论】:
int[] b = new int[3];
Array.Copy(a, 1, b, 0, 3);
【讨论】:
见this question。 LINQ Take() 和 Skip() 以及 Array.CopyTo() 是最受欢迎的答案。
【讨论】:
int[] a = {1,2,3,4,5};
int [] b= new int[a.length]; //New Array and the size of a which is 4
Array.Copy(a,b,a.length);
其中 Array 是具有方法 Copy 的类,它将数组的元素复制到 b 数组。
从一个数组复制到另一个数组时,您必须为要复制的另一个数组提供相同的数据类型。
【讨论】:
注意:我发现这个问题正在寻找如何调整大小现有数组的答案中的步骤之一。
所以我想我会在此处添加该信息,以防其他人正在寻找如何进行范围复制作为调整数组大小问题的部分答案。
对于其他找到这个问题并寻找与我相同的东西的人来说,这非常简单:
Array.Resize<T>(ref arrayVariable, newSize);
其中 T 是类型,即声明 arrayVariable 的位置:
T[] arrayVariable;
该方法处理 null 检查,以及 newSize==oldSize 无效,当然,它会静默处理其中一个数组比另一个数组长的情况。
请参阅the MSDN article 了解更多信息。
【讨论】:
如果你想实现自己的 Array.Copy 方法。
泛型的静态方法。
static void MyCopy<T>(T[] sourceArray, long sourceIndex, T[] destinationArray, long destinationIndex, long copyNoOfElements)
{
long totaltraversal = sourceIndex + copyNoOfElements;
long sourceArrayLength = sourceArray.Length;
//to check all array's length and its indices properties before copying
CheckBoundaries(sourceArray, sourceIndex, destinationArray, copyNoOfElements, sourceArrayLength);
for (long i = sourceIndex; i < totaltraversal; i++)
{
destinationArray[destinationIndex++] = sourceArray[i];
}
}
边界方法实现。
private static void CheckBoundaries<T>(T[] sourceArray, long sourceIndex, T[] destinationArray, long copyNoOfElements, long sourceArrayLength)
{
if (sourceIndex >= sourceArray.Length)
{
throw new IndexOutOfRangeException();
}
if (copyNoOfElements > sourceArrayLength)
{
throw new IndexOutOfRangeException();
}
if (destinationArray.Length < copyNoOfElements)
{
throw new IndexOutOfRangeException();
}
}
【讨论】: