Version 3 of String occurrences

Updated 2013-03-17 04:29:07 by AMG

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]

AMG: This gets into trouble when $needleString contains regular expression metacharacters, all of which will need to be preceded by backslashes. Try this:

regsub -all {[][{}()\\^$*+?.]} $needleString {\\&} needleString