VB中对string array快速插入、删除某个元素的办法

'作为测试,添加1个按钮,两个listbox
Private Declare Sub CopyMemory Lib "kernel32" Alias _
    "RtlMoveMemory" (dest As Any, source As Any, _
    ByVal numBytes As Long)

Sub InsertStringItem(strArr() As String, ByVal index As Long, _
        ByVal newItem As String)
    Dim lastItem As Long, saveAddr As Long
    lastItem = UBound(strArr)
    saveAddr = StrPtr(strArr(lastItem))
    CopyMemory ByVal VarPtr(strArr(index + 1)), ByVal _
        VarPtr(strArr(index)), (lastItem - index) * 4
    CopyMemory ByVal VarPtr(strArr(index)), saveAddr, 4
    strArr(index) = newItem
End Sub

Private Sub DeleteStringItem(strArr() As String, ByVal index As Long)
    Dim lastItem As Long, saveAddr As Long
    lastItem = UBound(strArr)
    saveAddr = StrPtr(strArr(index))
    CopyMemory ByVal VarPtr(strArr(index)), ByVal VarPtr(strArr(index + 1)), (lastItem - index) * 4
    CopyMemory ByVal VarPtr(strArr(lastItem)), saveAddr, 4
    strArr(lastItem) = vbNullString
End Sub


Private Sub Command1_Click()

    Dim a() As String
    ReDim a(5) '
    a(0) = "1 黄河远上"
    a(1) = "2 白云一片"
    a(2) = "3 孤城万仞山"
    a(3) = "4 羌笛何需怨"
    a(4) = "5 杨柳春风"
    a(5) = "6 不渡玉门关"
    '插入元素的时候先redim,再调用InsertStringIte
    ReDim Preserve a(UBound(a) + 1)
    InsertStringItem a, 1, "mc"
    '测试输出
    Dim i As Long
    For i = 0 To UBound(a)
        List1.AddItem "a(" + CStr(i) + ")=" + a(i)
    Next
    '删除元素的时候,先调用DeleteStringItem,再redim
    DeleteStringItem a, 2
    ReDim Preserve a(UBound(a) - 1)
     '测试输出
    For i = 0 To UBound(a)
        List2.AddItem "a(" + CStr(i) + ")=" + a(i)
    Next
End Sub


 

你可能感兴趣的:(String)