VB如何除去数组中相同的数
具体思路:
实现2次循环,一个数组循环2次,外循环数组,得出一个值a,然后内循环,将a与自身所在的数组的值对比一次,计算出现次数或者设置为空,如果计算出现次数可以计算次数大于2时候,进行删除操作。如果设置为空,等于进行删除操作。
具体代码如下:
Option Explicit
Function Delete3(Arr As Variant) As Variant
Dim i As Integer
For i = LBound(Arr) To UBound(Arr)
If i > UBound(Arr) Then Exit For //累计器大于数组长度,退出循环
If Arr(i) = 3 Then
Do
Dim j As Integer
For j = i To UBound(Arr) - 1 //数组从新赋值
Arr(j) = Arr(j + 1)
Next j
If LBound(Arr) = UBound(Arr) Then
Delete3 = Empty //删除相同元素
Exit Function
End If
ReDim Preserve Arr(LBound(Arr) To UBound(Arr) - 1)
//从新定义数组长度
If i > UBound(Arr) Then Exit For //累计器大于数组长度,退出循环
Loop While Arr(i) = 3
End If
Next i
Delete3 = Arr
End Function
Sub Test()
Delete3 (Array(3, 3, 3, 3, 1, 3, 7, 3, 3, 3, 9, 3, 3))
End Sub
测试结果:验证方式通过计算删除元素后的数组长度确认实现功能,输入了Array(3, 3, 3, 3, 1, 3, 7, 3, 3, 3, 9, 3, 3),长度为13(从1开始算),删除后长度为3,而且只有3个元素是不重复的。说明功能正常。
Dim BlnOk As Boolean
Dim IntTest(99) As Integer '未清除重复前的数组
Dim IntNew() As Integer '清除重复数后的数组
Dim i As Integer
Dim k As Integer
Dim a As Integer
For i = 0 To 99
IntTest(i) = Int(Rnd * 100) + 1 '为测试数组赋值
Next
For i = 0 To UBound(IntTest)
BlnOk = True
For k = 0 To UBound(IntTest)
If IntTest(i) = IntTest(k) And i <> k Then
BlnOk = False '有重复数出现,标志为假
Exit For
End If
Next
If BlnOk = True Then
'标志为真时 将数值加入新的数组
ReDim Preserve IntNew(a)
IntNew(a) = IntTest(i)
Debug.Print IntNew(a)
a = a + 1
End If
Next
dim nlength as integer
dim a() as integer
dim n as integer
n=100
redim a(n-1) as integer
'给数组赋值0--99。
nlength=n-1
for i=0 to nlength-1
for j=i+1 to nlength
if a(j)=a(i) then
for k=j to nlength-1
a(k)=a(k+1)
next k
nlength=nlength-1
end if
next j
next i
for i=0 to nlength
print a(i)
next i
'nlength为去除相同数后的数组长度
Dim s(1 To 10) As Integer
Dim i, j, k, n As Integer
s(1) = 1
s(2) = 44
s(3) = 1
s(4) = 2
s(5) = 3
s(6) = 5
s(7) = 44
s(8) = 66
s(9) = 66
s(10) = 7
n = 10
For i = 1 To n - 1
For j = i + 1 To n
If s(i) = s(j) Then
For k = j To n - 1
s(k) = s(k + 1)
Next k
n = n - 1
End If
Next j
Next i
For i = 1 To n
Print s(i)
Next i
End Sub