简体   繁体   中英

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.

How do I remove every 5th element of the array?

Thus, the end result should be an array of only 40 elements left, since every 5th element was taken out....

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'.

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) -

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM