[英]How do I copy the array elements and also reversing certain elements with Array.Copy() in c#?
Elements of SourceArray are being copied to 2 separate Arrays namely DestArray1 and DestArray2. SourceArray 的元素被复制到 2 个单独的数组中,即 DestArray1 和 DestArray2。
output:输出:
I want to replace the for loop with Array.Copy() method我想用 Array.Copy() 方法替换 for 循环
if not reversed then Array.Copy() works kind of fine except for the last element, but to copy with reverse, it seems the Array.Copy doesn't work or I am not able to implement it.如果没有反转,那么 Array.Copy() 除了最后一个元素之外工作得很好,但是要反向复制,似乎 Array.Copy 不起作用或者我无法实现它。
int i, j;
int bytelength =8;
int halfbytelength = 4;
byte[] SourceArray = new byte[]{ 1, 2, 3, 4, 5, 6, 7, 8 };
byte[] DestArray1 = new byte[4];
byte[] DestArray2 = new byte[4];
for (i = halfbytelength - 1, j = 0; i >= 0; i -= 1, j++)
{
DestArray1[j] = SourceArray[i];
}
for (i = halfbytelength; i < bytelength; i += 1)
{
DestArray2[i - halfbytelength] = SourceArray[i];
}
I tried following the code but the results are not as expected as seen in(Results:), is there a way to do it?我尝试按照代码进行操作,但结果与(结果:) 中看到的不一样,有没有办法做到这一点?
Array.Copy(SourceArray, 0, DestArray1, 3, 0);
Array.Copy(SourceArray, 4, DestArray2, 0, 3);
Result:结果:
DestArray1: [0 0 0 0]目标阵列 1:[0 0 0 0]
DestArray2: [5 6 7 0]目标阵列2:[5 6 7 0]
First array.第一个数组。
To reverse array you can just call Array.Reverse()
after copying:要反转数组,您可以在复制后调用Array.Reverse()
:
Array.Copy(SourceArray, 0, DestArray1, 0, 4);
Array.Reverse(DestArray1);
Second array.第二个数组。
if not reversed then Array.Copy() works kind of fine except for the last element如果不反转,那么 Array.Copy() 工作得很好,除了最后一个元素
Because you pass invalid count of elements to copy (last parameter):因为您传递了无效的元素计数来复制(最后一个参数):
Array.Copy(SourceArray, 4, DestArray2, 0, 3); // 3 - elements count, not an index
Simply replace 3 with 4:只需将 3 替换为 4:
Array.Copy(SourceArray, 4, DestArray2, 0, 4); // 4 and it will copy including the last element
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.