2012-12-13 94 views
2

我有这样的代码:VB6声明数组

' 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 

,但我得到一个错误时,因为字符数未声明使用Option Explicit,但我必须使用什么类型的暗淡数组(Dim Chars As ???????)?

+0

@george:感谢编辑,它看​​起来好多了...... – faid

回答

6

修正版本:

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 

总体性能更好的版本:

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 

理解变种是重要的,应该是特别有意识的使用变异版本的字符串函数而不是字符串类型版本后缀为“$”类型的装饰。

大多数情况下,由于性能成本,您可能需要避免变体。

该版本可能进行更好:

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 

没有“字符”类型的VB6,也没有在声明变量的初始化语法。

+0

哇,感谢您的建议哥们,我必须尝试这一切,它看起来更好... – faid

+0

为了好奇,我跑了不同版本再加上一个我用正则表达式写的。我使用这个测试字符串测试了它:“nc834u \ 7238/4037 *?”。 第一个版本花了30秒运行100,000次。 第二个和第三个版本每个都花费23秒来运行1,000,000次。 正则表达式需要17秒到100万次。适度增加。 我应该注意到,只有编译并运行时,增加才是明显的。在解释模式下运行时,它与版本2和3的运行时间相同。如果有人想要,我会在单独的注释中发布我的代码。 –

+0

'Function Clean1(S As String)As String Dim regex As New RegExp regex.Pattern =“[\\ /:\?\ * \”“\ <\> \ |]” 正则表达式。IgnoreCase = True regex.Global = True Clean1 = regex.Replace(S,“”) End Function' 注意:您必须添加对Microsoft VBScript Regular Expressions **的引用才能使其正常工作。 –

0

数组声明方式与其他变量(即使用关键字“Dim”,“Private”,“Public”等)的声明方式相同,只是数组边界使用变量名后面的括号编码(if一个固定长度的数组正在被声明),或者一对空括号用于变量名称(如果声明了可变长度或动态数组)。

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

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

+0

你的代码实际上**不起作用**,但感谢您的链接,现在我宣布它为'Variant' – faid

+0

而不是说它不起作用可以提供错误消息? –

+0

这是错误的,当我键入它,因为我的vb6不能在DIM之后有一个* equal * Dim'无论作为无论=无论',所以错误没有显示任何东西,它只是突出显示'='符号... – faid

1

你可以调暗它作为一个字符串数组 你不会需要一个变种这样做

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