| Answer: |
One way to determine whether or not an array contains an element or not is to use a simple For ... Next loop to iterate through each element of the array, checking to see if the element is equal to a particular string. A simple example of this follows:
Dim iLoop, bolFound bolFound = False
For iLoop = LBound(SomeArray) to UBound(SomeArray) If CStr(SomeArray(iLoop)) = CStr(SomeString) then bolFound = True End If Next
|
By the time this code completes, bolFound will be True if SomeString was found in SomeArray, and False otherwise. This will perform a case-sensitive comparison, though, so if we are searching for "FooBar" and the array contains an element equal to "Foobar", the bolFound will be False.
In an earlier FAQ, we examined how to determine the position of a particular string element in an array. This function can be used to quickly determine whether or not a string element exists in the array. Check out the FAQ and note that we can create our own function like so:
Function ElementInArray(aMyArray, strLookingFor, compare) 'Returns True if strLookingFor is in aMyArray, False otherwise ElementInArray = (PositionInArray(aMyArray, strLookingFor, compare) > -1) End Function
|
This makes use of the function PositionInArray, which we created in a past FAQ.
We can also use the Filter function to accomplish something similar. I won't go into detail on how the Filter function works (for more detail be sure to read Filtering Arrays with Filter!):
Function ElementInArray(aMyArray, strLookingFor, compare) 'Returns True if strLookingFor is in aMyArray, False otherwise ElementInArray = (UBound(Filter(aMyArray, strLookingFor, True, compare)) > -1) End Function
|
There you have it! Three techniques that you can use to quickly determine if a particular string exists in an array!
Happy Programming! |