2016-01-15 54 views
1

我想知道在另一個字符串中出現了多少次,哪個Tcl似乎沒有內置。我不能使用wiki上的任一解決方案,因爲我必須支持Tcl 8.0。Tcl 8.0上計算子字符串的出現次數

這不起作用:

# needleString is known to contain no regex metacharacters 
llength [regexp -all -inline $needleString $haystackString] 

因爲-all不支持8.0。

這不起作用:

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 
} 

因爲string first不支持8.0 startIndex說法。

我可以修改string_occurrences使用string range採取字符串和2論證string first的子裏面的搜索,但比環已經是這更麻煩了,我不知道string range是多麼有效。我有更好的選擇嗎?

+0

8.0嗎?哇!你在沒有地勤人員的情況下獨自飛行... –

+0

@DonalFellows:我希望自己沒有陷入1997年的一個版本,但這就是我們的測試基礎架構所說的。 – user2357112

+0

tcl 8.0手冊頁:http://www.tcl.tk/man/tcl8.0/TclCmd/contents.htm –

回答

2

你可以使用[regsub -all](這是目前在8.0),創建與刪除needleString一個新的字符串,並且比較長:

proc string_occurrences {needleString haystackString} { 
    regsub -all $needleString $haystackString {} stripped 
    expr {([string length $haystackString] - [string length $stripped])/[string length $needleString]} 
} 
相關問題