程序代码如下:
Dim a()
Private Sub Form_Load()
ReDim Preserve a(1 To 5)
For i = 1 To 5
a(i) = i
Next i
For i = 1 To 5
Text1.Text = Text1.Text & "a(" & i & ")=" & a(i) & "; "
Next i
For i = 2 To 4
a(i) = a(i + 1)
Next i
ReDim Preserve a(1 To 4)
For i = 1 To 4
Text2.Text = Text2.Text & "a(" & i & ")=" & a(i) & "; "
Next i
End Sub
算法总结:
1、插入数组元素和删除数组元素都使用循环交换,插入数组元素是原数组元素往后移动,删除数组元素是将原数组的元素往前移动。
2、插入数组元素,需要先将数组长度加长再增加数组元素;删除数组元素,可以先删除数组元素,再建数组长度缩短。
扩展资料:
数组中元素的插入和删除一般是在己固定序列的数组中插入或除一个元素,使得插入或删除操作后的数组还是有序的。
1、插入
代码如下:
Private Sub Command1 click)
Dim a(10)As Integer
Dim i As Integer, k As Integer
For i = 0 To 9
a(i) = i*3 +1
Print a(i)
Next i
Print"插入14"
For k =0 To 9
If 14 < a(k) Then Exit For
Next k
For i = 9 To k Step 从最后元素开始逐个后移腾出位置
a(i+1)=a(i)
Next i
Sub Macro1()
Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim a(5) As Variant
Dim b() As Variant
’初始化数组a()
a(0) = 1
a(1) = 2
a(2) = 1
a(3) = 3
a(4) = 2
a(5) = 3
k = 0
'将重复元素替换为空
For i = 0 To UBound(a)
For j = i + 1 To UBound(a)
If a(i) = a(j) Then
a(j) = ""
End If
Next j
Next i
‘比较,不为空的元素添加到新的数组中
For i = 0 To UBound(a)
If a(i) <> "" Then
ReDim Preserve b(k)
b(k) = a(i)
k = k + 1
End If
Next i
’打印输出新数组的元素
For i = 0 To UBound(b)
Debug.Print b(i)
Next i
End Sub
一楼好麻烦,看着就害怕。简洁有效才是源码王道
Private Sub Form_Click()
Dim A(), B(),I,J As Integer
Dim Temp As String
A = Array(1, 1, 1, 2, 2, 3, 3, 3, 4, 4)//你可以换成其他数字试试,都是对的
For I = 0 To UBound(A)
For J = I + 1 To UBound(A)
If A(I) = A(J) Then A(J) = "@"
Next
Next
Temp = Replace(Join(A, ""), "@", ""):ReDim B(Len(Temp) - 1)
For I = 1 To Len(Temp)
B(I - 1) = CInt(Mid(Temp, I, 1))
Next
MsgBox "数组B的成员:" & Join(B)
End Sub
dim j as integer
j=1
for i=1 to len(a)-1
for m=i+1 to len(a)
if a(i)=a(m)then
exit for
endif
b(j)=a(i)
j=j+1
next m
next i
b(j)=a(len(a))
我大概的想法。还没有试过。