Title | Determine whether an array of strings contains an item in a clever way |
Description | This example shows how to determine whether an array of strings contains an item in a clever way in Visual Basic 6. The program compares this technique to a more straightforward method that is less clever but faster. |
Keywords | array contains, array, contains |
Categories | Utilities, Miscellany, Algorithms |
|
|
The ArrayContainsJoin function uses Join to combine the values in an array into a delimited string. It then uses InStr to search for a target string within the combined result.
|
|
' Return True if the target is in the array.
Public Function ArrayContainsJoin(values() As String, ByVal _
target As String) As Boolean
Dim combined As String
combined = vbNullChar & Join(values, vbNullChar) & _
vbNullChar
target = vbNullChar & target & vbNullChar
ArrayContainsJoin = (InStr(combined, target) > 0)
End Function
|
|
The ArrayContainsLoop function loops through the array looking for the target string.
|
|
' Return True if the target is in the array.
Public Function ArrayContainsLoop(values() As String, ByVal _
target As String) As Boolean
Dim i As Integer
' Assume we will find the target.
ArrayContainsLoop = True
For i = LBound(values) To UBound(values)
If values(i) = target Then Exit Function
Next i
' We didn't find the target.
ArrayContainsLoop = False
End Function
|
|
While ArrayContainsJoin is certainly sneaky, it takes about 20 percent longer than ArrayContainsLoop in my tests. The moral is: just because something is clever and concise doesn't mean it's faster than the straightforward approach.
|
|
|
|