Can the Instr function handle multiple strings to find?

emaduddeen

Well-known member
Joined
May 5, 2010
Messages
171
Location
Lowell, MA & Occasionally Indonesia
Programming Experience
Beginner
Hi Everyone,

I'm using this for a single value to search for.

VB.NET:
       intPositionOfApartment = InStr(StrConv(pStringToParse, vbUpperCase), "APT")

Is it possible to search for more then one value such as "APT", "UNIT" ?

If yes please show me an example of how it should be coded.

Thanks.

Truly,
Emad
 
You'll only be able to search for each one separately:
VB.NET:
Dim intAPT As Integer = pStringToParse.ToUpper.IndexOf("APT")
Dim intUNIT As Integer = pStringToParse.ToUpper.IndexOf("UNIT")
intAPT will be greater than -1 if "APT" exists and intUNIT will be greater than -1 if UNIT exists.
 
Hi,

Thanks for helping. Maybe we can send a request to MS to include something like this if they read vbdotnetforums.com:

VB.NET:
intPositionOfApartment = InStr(StrConv(pStringToParse, vbUpperCase), "APT", "UNIT", "#","And so on")

Truly,
Emad
 
There is a String.IndexOfAny method but it is only for single characters, not substrings. I would assume that there was a specific reason for that, given that IndexOf supports Chars and Strings. That said, you could always create your own extension method. Every developer should have their own library of extension methods for common types that they can reference in any other project.
VB.NET:
Imports System.Runtime.CompilerServices

Public Module StringExtensions

    <Extension()> _
    Public Function IndexOfAny(ByVal sender As String, ByVal ParamArray anyOf As String()) As Integer
        Dim index = -1

        If anyOf IsNot Nothing AndAlso anyOf.Length > 0 Then
            For Each substring In anyOf
                index = sender.IndexOf(substring)

                If index <> -1 Then Exit For
            Next
        End If

        Return index
    End Function

    <Extension()> _
    Public Function IndexOfAny(ByVal sender As String, ByVal comparisonType As StringComparison, ByVal ParamArray anyOf As String()) As Integer
        Dim index = -1

        If anyOf IsNot Nothing AndAlso anyOf.Length > 0 Then
            For Each substring In anyOf
                index = sender.IndexOf(substring, comparisonType)

                If index <> -1 Then Exit For
            Next
        End If

        Return index
    End Function

End Module
Example usage:
VB.NET:
If myString.IndexOfAny(StringComparison.CurrentCultureIgnoreCase, "Peter", "Paul", "Mary") <> -1 Then
 
Back
Top