Version 0 of String occurrences

Updated 2013-03-16 10:00:08 by WJG

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
}