Jump to content

_StringCount function


sohfeyr
 Share

Recommended Posts

StringInStr() is good for finding if and where one string occurs in another, but what if you want to know how many times the substring occurs?

These are two different functions that do the same thing. Both are very simple, but the contrast could be good for a tutorial or something. The second is more elegant, but the first would be easier to understand for someone who is new to AutoIt.

ConsoleWrite(_StringCount("123123412345","2") & @crlf)
ConsoleWrite(_StringCount2("123123412345","2") & @crlf)

Func _StringCount($myString, $SearchFor, $casesense=0) 
    Local $max = StringLen($myString)
    Local $len = StringLen($SearchFor)
    Local $count = 0
    
    If $casesense=0 Then
        $myString = StringUpper($myString)
        $SearchFor = StringUpper($SearchFor)
    EndIf
    
    For $x = 1 to $max-$len+1
        If StringMid($myString,$x,$len) = $SearchFor then
            $count += 1
        EndIf
    Next
    Return $count 
EndFunc

Func _StringCount2($myString, $SearchFor, $casesense=0)
    Local $count = 0
    While StringInStr ($myString, $SearchFor, $casesense, $count+1) > 0
        $count += 1
    WEnd
    Return $count
EndFunc
Link to comment
Share on other sites

here's also an elegant way :lmao:

Func _StringCount($myString, $SearchFor, $casesense=0) 
     local $text = StringReplace($myString, $SearchFor, "-",0,$casesense)
     return @extended
EndFunc

Almost direct from Help file of StringReplace().

Cheers

Kurt

Edited by /dev/null

__________________________________________________________(l)user: Hey admin slave, how can I recover my deleted files?admin: No problem, there is a nice tool. It's called rm, like recovery method. Make sure to call it with the "recover fast" option like this: rm -rf *

Link to comment
Share on other sites

here's also an elegant way ph34r.gif

CODE: AutoIt

Func _StringCount($myString, $SearchFor, $casesense=0)

local $text = StringReplace($myString, $SearchFor, "-",0,$casesense)

return @extended

EndFunc

Almost direct from Help file of StringReplace().

Cheers

Kurt

That is exactly what I was thinking!

What goes around comes around... Payback's a bitch.

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...