因此,获取另一个字符串中的字符串实例的方法是使用此String类扩展:
func indexOf(target: String) -> Int? {
let range = (self as NSString).range(of: target)
guard range.toRange() != nil else {
return nil
}
return range.location
}
但是,现在我正在寻找一种在字符串中获取字符串的第n个实例的方法。例如,如果我想在“展示房屋中的房屋显示陌生人”中获取“房屋”的第三个实例的索引。我该怎么做?
一种可能的解决方案,可以直接在Swift上运行String
,而无需桥接NSString
(也无需创建临时子字符串):
extension String {
func index(of target: String, instance: Int = 1) -> Int? {
precondition(!target.isEmpty)
precondition(instance > 0)
var found = 0 // Number of occurrences found so far.
var pos = startIndex // Current search position.
// Search for next occurrence of `target`.
while let r = range(of: target, range: pos..<endIndex) {
found += 1
// Are we done?
if found == instance {
// Distance in # of characters:
return distance(from: startIndex, to: r.lowerBound)
}
// Continue search after this occurrence.
pos = r.upperBound
}
return nil
}
}
例子:
let bStr = "Houses on the show Dr. House's PlayHouse house strange people"
let ls = "House"
if let idx = bStr.index(of: ls, instance: 3) {
print(idx) // 35
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句