简体   繁体   中英

vb6 Declare an Array

I have this code :

' Option Explicit
Public Function Clean(Text)
    On Error Resume Next
    ' Dim Chars As ?????????
    Chars = Array("\", "/", ":", "*", "?", """", "<", ">", "|")
    For Each Replaced In Chars
        Text = Replace(Text, Replaced, "")
    Next
    Clean = CStr(Text)
End Function

But i got an error when use Option Explicit because the Chars is not declared, but what type must i use to dim an array ( Dim Chars As ??????? )?

Corrected version:

Option Explicit

Public Function Clean(ByVal Text As String)
    Dim Chars As Variant
    Dim Replaced As Variant

    Chars = Array("\", "/", ":", "*", "?", """", "<", ">", "|")
    For Each Replaced In Chars
        Text = Replace(Text, Replaced, "")
    Next
    Clean = Text
End Function

Generally better performing version:

Option Explicit

Public Function Clean(ByVal Text As String)
    Dim Chars As Variant
    Dim RepIndex As Long

    Chars = Array("\", "/", ":", "*", "?", """", "<", ">", "|")
    For RepIndex = 0 To UBound(Chars)
        Text = Replace$(Text, Chars(RepIndex), "")
    Next
    Clean = Text
End Function

Understanding Variants is important, and one should be especially conscious of using the Variant version of string functions instead of the String-typed versions suffixed with the "$" type decoration.

Most of the time you'll want to avoid Variants when you can because of performance costs.

This version probably performs even better:

Option Explicit

Public Function Clean(ByVal Text As String)
    Const Chars As String = "\/:*?""<>|"
    Dim RepIndex As Long

    For RepIndex = 1 To Len(Chars)
        Text = Replace$(Text, Mid$(Chars, RepIndex, 1), "")
    Next
    Clean = Text
End Function

There is no "Char" type in VB6, nor is there any initialization syntax on variable declaration.

you can dim it as an array of strings you won't need a variant to do so

Dim Chars() As String
Chars = Split("\,/,:,*,?,"",<,>,|", ",")

Arrays are declared in the same manner as other variables (ie using the keywords "Dim", "Private", "Public", etc.), except that the array bounds are coded in parentheses following the variable name (if a fixed-length array is being declared) or an empty pair of parentheses follow the variable name (if a variable-length, or dynamic array is being declared).

 Dim Chars As Variant
 Chars = Array("\", "/", ":", "*", "?", """", "<", ">", "|")

http://www.vb6.us/tutorials/understanding-arrays

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