Version 2 of String occurrences

Updated 2013-03-17 03:54:09 by SEH

WJG (16/03/13) Needed a simple way of counting the occurrences of one string in another. I was surprised to find that the standard Tcl string command had no offering.

proc string_occurrences {needleString haystackString} {

        set j [string first $needleString $haystackString 0]
        if {$j == -1} {return 0}
        
        set i 0                
        while {$j != -1 } { 
                set j [string first $needleString $haystackString [incr j]] 
                incr i
        } 

        return $i
}

SEH How about:

 llength [regexp -all -inline (?=$needleString) $haystackString]