如何检测字符串中单词的多次出现

Luc*_*rdi 2 string range swift

我已经寻找了一段时间,想知道如何在较大的字符串中检测子字符串的多个位置。例如:

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"
Run Code Online (Sandbox Code Playgroud)

我使用此代码来检测子字符串出现在字符串中的第一个位置,但是可以检测第二个出现的“操场”的位置,然后检测第三个出现的位置,依此类推?

Str*_*ers 5

这应该为您提供带有“操场”的NSRanges阵列

let regex = try! NSRegularExpression(pattern: "playground", options: [.CaseInsensitive])
let items = regex.matchesInString(text, options: [], range: NSRange(location: 0, length: text.characters.count))
let ranges: [NSRange] = items.map{$0.range}
Run Code Online (Sandbox Code Playgroud)

然后获取字符串:

let occurrences: [String] = ranges.map{String((text as NSString).substringWithRange($0))}
Run Code Online (Sandbox Code Playgroud)