Version 4 of String occurrences

Updated 2013-03-17 05:40:18 by pooryorick

WJG 2013-03-16: 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

PYK: Another option is ycl::string::delimit:

package require ycl::string
namespace import [yclprefix]::string::delimit

set data "one and two and three and four andand five"
delimit $data string and format count
# 5