Consider the following:
If myString = "abc" Or myString = "def" [...] Or myString = "xyz" Then
In C# when myString == "abc"
the rest of the conditions aren't evaluated. But because of how VB works, the entire expression needs to be evaluated, even if a match is found with the first comparison.
Even worse:
If InStr(1, myString, "foo") > 0 Or InStr(1, myString, "bar") > 0 [...] Then
I hate to see these things in code I work with. So I came up with these functions a while ago, been using them all over the place, was wondering if anything could be done to make them even better:
StringContains is used like If StringContains("this is a sample string", "string")
:
Public Function StringContains(string_source, find_text, Optional ByVal caseSensitive As Boolean = False) As Boolean
'String-typed local copies of passed parameter values:
Dim find As String, src As String
find = CStr(find_text)
src = CStr(string_source)
If caseSensitive Then
StringContains = (InStr(1, src, find, vbBinaryCompare) <> 0)
Else
StringContains = (InStr(1, src, find, vbTextCompare) <> 0)
End If
End Function
StringContainsAny works in a very similar way, but allows specifying any number of parameters so it's used like If StringContainsAny("this is a sample string", false, "foo", "bar", string")
:
Public Function StringContainsAny(string_source, ByVal caseSensitive As Boolean, ParamArray find_strings()) As Boolean
'String-typed local copies of passed parameter values:
Dim find As String, src As String, i As Integer, found As Boolean
src = CStr(string_source)
For i = LBound(find_strings) To UBound(find_strings)
find = CStr(find_strings(i))
If caseSensitive Then
found = (InStr(1, src, find, vbBinaryCompare) <> 0)
Else
found = (InStr(1, src, find, vbTextCompare) <> 0)
End If
If found Then Exit For
Next
StringContainsAny = found
End Function
StringMatchesAny will return True
if any of the passed parameters exactly matches (case-sensitive) the string_source
:
Public Function StringMatchesAny(string_source, ParamArray find_strings()) As Boolean
'String-typed local copies of passed parameter values:
Dim find As String, src As String, i As Integer, found As Boolean
src = CStr(string_source)
For i = LBound(find_strings) To UBound(find_strings)
find = CStr(find_strings(i))
found = (src = find)
If found Then Exit For
Next
StringMatchesAny = found
End Function