|
Language: VB7 Expertise: Intermediate
Oct 27, 2003
ArrayIndexOf - An extended version of Array.IndexOf
' An extended version of Array.IndexOf, with more options for string searches.
' The function returns the index of the found element,
' or -1 if no element is found
'
' Example:
' Dim arr As String() = {"this is a string for my test", "test number 2",
' "another String", "do you like this string?", "I like running tests"}
' Dim i As Integer = -1
' Do
' i = ArrayIndexOf(arr, "string", i + 1, False, False)
' If i > -1 Then
' Debug.WriteLine(arr(i))
' End If
' Loop While i > -1
Function ArrayIndexOf(ByVal arr As String(), ByVal search As String) As Integer
Return ArrayIndexOf(arr, search, arr.GetLowerBound(0))
End Function
' this overloaded version allows you to specify also the array's index to start
' from
Function ArrayIndexOf(ByVal arr As String(), ByVal search As String, _
ByVal startIndex As Integer) As Integer
Return ArrayIndexOf(arr, search, startIndex, True)
End Function
' this overloaded version allows you to specify also whether the search is case-
' sensitive
Function ArrayIndexOf(ByVal arr As String(), ByVal search As String, _
ByVal startIndex As Integer, ByVal caseSensitive As Boolean) As Integer
Return ArrayIndexOf(arr, search, startIndex, caseSensitive, True)
End Function
' this overloaded version allows you to specify also whether only exact matches
' are valid
Function ArrayIndexOf(ByVal arr As String(), ByVal search As String, _
ByVal startIndex As Integer, ByVal caseSensitive As Boolean, _
ByVal exactMatch As Boolean) As Integer
' if the search is case-sensitive and it runs against exact matches only,
' use the standard Array.IndexOf function
If caseSensitive And exactMatch Then
Return Array.IndexOf(arr, search, startIndex)
End If
If Not caseSensitive Then search = search.ToLower()
Dim lastIndex As Integer = arr.GetUpperBound(0)
Dim i As Integer
For i = startIndex To lastIndex
Dim currElem As String = arr(i)
' if the search is not case-sensitive, convert everything to lower-case
If Not caseSensitive Then currElem = currElem.ToLower()
If exactMatch Then
If search = currElem Then Return i
Else
' if partial matches are ok, use the String.IndexOf function,
' and return the
' current index if a partial match is found
Dim j As Integer = currElem.IndexOf(search)
If j > -1 Then Return i
End If
Next
' if we get here, no element matches the search options, so return -1
Return -1
End Function
Marco Bellinaso
|