What is the best way to clear an array of strings?

后端 未结 7 1357
被撕碎了的回忆
被撕碎了的回忆 2021-02-19 02:13

What is the best way to clear an array of strings?

相关标签:
7条回答
  • 2021-02-19 02:46

    And of course there's the VB way using the Erase keyword:

    Dim arr() as String = {"a","b","c"}
    Erase arr
    
    0 讨论(0)
  • 2021-02-19 02:52

    redim arr(1,1,1,1) and then redim (z,x,y,v) to your dimensions

    0 讨论(0)
  • 2021-02-19 02:56

    If you're needing to do things like clear, you probably want a collection like List(Of String) rather than an array.

    0 讨论(0)
  • 2021-02-19 02:58

    If you need to reinitialize with empty strings or other values not equal to Nothing/Null, you may get further using an extension method:

    Option Strict On : Option Explicit On : Option Infer On
    ...
    Public Delegate Sub ArrayForAllDelegate(Of T)(ByRef message As T)
    <Extension>
    Public Function ForAll(Of T)(ByRef self As T(), f As ArrayForAllDelegate(Of T)) As T()
        Dim i = 0
        While i < self.Length
            f(self(i))
            i += 1
        End While
        Return self
    End Function
    

    Then your initialization code:

    Dim a = New String(3 - 1) {"a", "b", "c"}
    ...
    a.ForAll(Sub(ByRef el) el = "") 'reinitialize the array with actual empty strings
    
    0 讨论(0)
  • 2021-02-19 03:01

    Wrong way:

    myArray = Nothing 
    

    Only sets the variable pointing to the array to nothing, but doesn't actually clear the array. Any other variables pointing to the same array will still hold the value. Therefore it is necessary to clear out the array.

    Correct Way

    Array.Clear(myArray,0,myArray.Length)
    
    0 讨论(0)
  • 2021-02-19 03:06

    Here's a simple call that I use to clear the contents of a string array:

    Public Sub ClearArray(ByRef StrArray As String())
        For iK As Int16 = 0 To StrArray.Length - 1
            StrArray(iK) = ""
        Next
    End Sub
    

    Then just call it with:

    ClearArray(myLocalArray)
    
    0 讨论(0)
提交回复
热议问题