Jump to content

Search an array for multiple substrings


CYCho
 Share

Recommended Posts

I have a 1-dimensional array($array) with about 15, 000 elements. Each element is a string of 5 to 20 words. I made a function to find the 1st element in $array which contains all the words in a substring($substr) as follows. This works OK, but I would like to know if there is a more efficient way of doing it.

Global $string = FindString("This is a smaple substring")
If $string = '' Then
    MsgBox(0, '', 'Not found!')
Else
    MsgBox(0, '', $string)
EndIf

Func FindString($substr)
    $substr = StringSplit($substr, ' ')
    For $i = 1 To $array[0]
        $found = True
        For $j = 1 To $substr[0]
            If StringInStr($array[$i], $substr[$j]) Then
                $found = $found And True
            Else
                $found = $found And False
                ExitLoop
            EndIf
        Next
        If $found Then
            Return $array[$i]
        EndIf
    Next
EndFunc


 




 

Edited by CYCho
Link to comment
Share on other sites

You have a logical issue, corrected here:

Func FindString($substr)
    $substr = StringSplit($substr, ' ')
    For $i = 1 To $array[0]
        $found = True
        For $j = 1 To $substr[0]
            If Not StringInStr($array[$i], $substr[$j]) Then
                $found = False
                ExitLoop
            EndIf
        Next
        If $found Then
            Return $array[$i]
        EndIf
    Next
EndFunc

This is also more efficient, since you exit looking for the other words as soon as you don't find one of them.

 

Edit: on second review, you have no logic issues.  I've never seen setting the $found like that.  My example will still do the minimal amounts of loops on the stringsplit array.

Edit2: you can also switch out the ExitLoop with "ContinueLoop 2" to bypass the If $found Then statement...which would save a few milliseconds when potentially executed thousands of times.

Edited by jdelaney
IEbyXPATH-Grab IE DOM objects by XPATH IEscriptRecord-Makings of an IE script recorder ExcelFromXML-Create Excel docs without excel installed GetAllWindowControls-Output all control data on a given window.
Link to comment
Share on other sites

You are right! How come I did it that way! Thank you!

 

Edit: Now I come to think of the reason why I did that. If there were multiple number of elements satisfying the condition coming in succession, your code will come up with the last one, not the first one.

Edited by CYCho
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...