|
A very simple way
of determining whether or not a string exists in an array is to use a loop to check each element:
Dim iLoop, iPos
iPos = -
For iLoop =
LBound(SomeArray) to UBound(SomeArray)
If CStr(SomeString) = CStr(SomeArray(iLoop)) then
'We found the element
iPos = iLoop
End If
Nex
iPos will equal
the position that SomeString was found in SomeArray; or, if the string was
not found in the array, iPos will equal -1.
The following
function can be used to quickly determine the position that an element exists in an array:
Function
PositionInArray(aMyArray, strLookingFor, compare)
'Return the position strLookingFor is found in aMyArray... if
'strLookingFor is not found, -1 is returned
Dim iUpper, iLoop
iUpper = UBound(aMyArray)
For iLoop =
LBound(aMyArray) to iUpper
If compare = vbTextCompare then
If CStr(UCase(aMyArray(iLoop))) = CStr(UCase(strLookingFor)) then
PositionInArray = iLoop
Exit Function
End If
Else
If CStr(aMyArray(iLoop)) = CStr(strLookingFor) then
PositionInArray = iLoop
Exit Function
End If
End If
Nex
'Didn't find the
element in the array...
PositionInArray = -
End Function
NOTE: The function expects three parameters:
|
1.
|
aMyArray, the string array we are searching
|
|
2.
|
strLookingFor, the string that we are looking for in the array
aMyArray
|
|
3.
|
compare, which indicates that we want to do a case-sensitive search
(vbBinaryCompare) or a case-insensitive search (vbTextCompare)
|
Here is an example program for the above
function:
<%
'******* INCLUDE ABOVE FUNCTION IN CODE HERE *********
Dim aSomeArray
aSomeArray = Array("I", "think", "APlus.Net",
"is", "cool!"
Response.Write
PositionInArray(aSomeArray, "I", vbBinaryCompare) &
"<BR>"
Response.Write PositionInArray(aSomeArray, "foo", vbBinaryCompare)
& "<BR>"
Response.Write PositionInArray(aSomeArray, "ASP", vbBinaryCompare)
& "<BR>"
Response.Write PositionInArray(aSomeArray, "bar", vbBinaryCompare)
& "<BR>"
Response.Write PositionInArray(aSomeArray, "Cool!", vbTextCompare)
& "<BR>"
%>
Output is:
0
-1
2
-1
|