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

时间:2016-03-02 22:05:40

标签: string swift range

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

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"

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

2 个答案:

答案 0 :(得分:5)

这应该会为你提供一系列带有&#34; playground&#34;

的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}

然后得到字符串:

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

答案 1 :(得分:1)

雨燕4

let regex = try! NSRegularExpression(pattern: fullNameArr[1], options: [.caseInsensitive])
let items = regex.matches(in: str, options: [], range: NSRange(location: 0, length: str.count))
let ranges: [NSRange] = items.map{$0.range}
let occurrences: [String] = ranges.map{String((str as NSString).substring(with: $0))}