如何将数组的一部分复制到另一个数组?
假设我有以下数组:
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);
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 数组中。
在从一个数组复制到另一个数组时,必须为你要复制到的另一个数组提供相同的数据类型。
int a[] = {1,2,3,4,5};
int b[] = a[1..4]; // b = [2,3,4];
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/ranges
Array.Resize<T>(ref arrayVariable, newSize);
其中T是类型,即arrayVariable被声明的地方:
T[] arrayVariable;
如果您想要实现自己的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();
}
}