我一直在尋找一段時間,並想知道如何檢測更大字符串中的子字符串的多個位置。例如:如何檢測字符串中某個單詞的多次出現
let text = "Hello, playground. Hello, playground"
let range: Range<String.Index> = text.rangeOfString("playground")! //outputs 7...<17
let index: Int = text.startIndex.distanceTo(range.startIndex) //outputs 7, the location of the first "playground"
我使用此代碼來檢測子串出現在字符串中的第一個位置,但它有可能檢測的「運動場」的第二次出現的位置,然後將第三等等等?
Objective-C的答案在這裏,但邏輯也適用同樣的方式: NSString中子字符串的出現次數?](http://stackoverflow.com/questions/2166809/number-of-occurrences-of-a-substring-in-an-nsstring) – JAL