[英]How do I remove every 5th element from an array in Visual Basic?
I have an array of X elements, and let's say X = 50.我有一个 X 元素数组,假设 X = 50。
How do I remove every 5th element of the array?如何删除数组的每 5 个元素?
Thus, the end result should be an array of only 40 elements left, since every 5th element was taken out....因此,最终结果应该是一个只剩下 40 个元素的数组,因为每 5 个元素都被取出......
The code below isn't tested but it should be pretty close, after the code has run all non divisible by 5 elements will be contained in array 'strSecond'.下面的代码未经测试,但应该非常接近,在代码运行后,所有不可被 5 整除的元素都将包含在数组“strSecond”中。
UPDATE更新
Code below has now been tested -下面的代码现在已经过测试 -
Dim strFirst(49) As String
Dim strSecond() As String
Dim ArrCount As Integer
ArrCount = 0
For i = 1 To 50
strFirst(i - 1) = i
Next
For i = 0 To 49
If (i + 1) Mod 5 <> 0 Then
ReDim Preserve strSecond(ArrCount)
strSecond(ArrCount) = strFirst(i)
ArrCount = ArrCount + 1
End If
Next
For i = 0 To UBound(strSecond)
Debug.Print strSecond(i)
Next
UPDATE II更新二
This would work for a multi-dimensional array (only the upper bound of the last dimension in a multidimensional array can be changed when you use the Preserve keyword) -这适用于多维数组(使用 Preserve 关键字时,只能更改多维数组中最后一维的上限) -
Dim strFirst(1, 49) As String
Dim strSecond() As String
Dim ArrCount As Integer
ArrCount = 0
For i = 1 To 50
strFirst(0, i - 1) = i
strFirst(1, i - 1) = i
Next
For i = 0 To 49
If (i + 1) Mod 5 <> 0 Then
ReDim Preserve strSecond(1, ArrCount)
'If you have more than two dimensions could write a loop to do this
'For j = 0 To UBound(strFirst,1) etc
strSecond(0, ArrCount) = strFirst(0, i)
strSecond(1, ArrCount) = strFirst(1, i)
ArrCount = ArrCount + 1
End If
Next
For i = 0 To UBound(strSecond, 2)
Debug.Print strSecond(0, i) + "-" + strSecond(1, i)
Next
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.