爲雨燕另一種解決方案,我覺得很繁瑣與串& String.Index斯威夫特! !
let myString = "gffffsfjjjjjjfsfffffffsjjjjfs"
let subString = "fs"
let strLen = countElements(myString)
//init search range : the whole string
var searchRange = Range(start:advance(myString.startIndex,0), end: advance(myString.startIndex, strLen))
var foundRange = myString.rangeOfString(subString, options: NSStringCompareOptions.CaseInsensitiveSearch, range: searchRange, locale: nil)
var i: Int = 0;
while ((foundRange?.isEmpty) != nil) {
i++
//recaculate searchRange
searchRange = Range(start:advance(foundRange!.endIndex ,0), end: advance(myString.startIndex, strLen))
foundRange = myString.rangeOfString(subString, options: NSStringCompareOptions.CaseInsensitiveSearch, range: searchRange, locale: nil)
}
NSLog("Count = \(i)")
//擴展版本
extension String {
func countOccurent(_subString : String) -> Int {
let strLen = countElements(self)
//init search range : the whole string
var searchRange = Range(start:advance(self.startIndex,0), end: advance(self.startIndex, strLen))
var foundRange = self.rangeOfString(_subString, options: NSStringCompareOptions.CaseInsensitiveSearch, range: searchRange, locale: nil)
var i: Int = 0;
while ((foundRange?.isEmpty) != nil) {
i++
//re-caculate searchRange
searchRange = Range(start:advance(foundRange!.endIndex ,0), end: advance(self.startIndex, strLen))
foundRange = self.rangeOfString(_subString, options: NSStringCompareOptions.CaseInsensitiveSearch, range: searchRange, locale: nil)
}
NSLog("Result = \(i)")
return i
}
}
是的。我也在想這個。儘管有一些搜索詞出現,但對於長字符串可能效率很低。 – Fogmeister 2015-02-23 23:35:10
這似乎工作得很好 - 我會嘗試將其實施到我的代碼中。我可以問什麼(substring,substringRange,_,_)是什麼? – CodeIt 2015-02-24 19:36:10