let fullString = "Hello world, there are \(string(07)) continents and \(string(195)) countries."
let range = [NSMakeRange(24,2), NSMakeRange(40,3)]
需要为整个字符串中的数字找到NSRange,并且两个数字都可能相同。目前如上所示的硬编码,消息可以是动态的,其中硬编码值将是有问题的。
我已拆分字符串并尝试获取NSRange
,因为可能存在相同的值。比如stringOne和stringTwo。
func findNSMakeRange(initialString:String, fromString: String) {
let fullStringRange = fromString.startIndex..<fromString.endIndex
fromString.enumerateSubstrings(in: fullStringRange, options: NSString.EnumerationOptions.byWords) { (substring, substringRange, enclosingRange, stop) -> () in
let start = distance(fromString.startIndex, substringRange.startIndex)
let length = distance(substringRange.startIndex, substringRange.endIndex)
let range = NSMakeRange(start, length)
if (substring == initialString) {
print(substring, range)
}
})
}
收到Cannot invoke distance with an argument list of type (String.Index, String.Index)
任何人都有更好的解决方案吗?
答案 0 :(得分:3)
另一种方法是定义一个扩展来返回一个范围数组,即[Range<String.Index>]
:
extension StringProtocol where Index == String.Index {
func ranges<T: StringProtocol>(of string: T, options: String.CompareOptions = []) -> [Range<Index>] {
var ranges: [Range<Index>] = []
var start: Index = startIndex
while let range = range(of: string, options: options, range: start..<endIndex) {
ranges.append(range)
start = range.upperBound
}
return ranges
}
}
然后你可以像这样使用它:
let string = "Hello world, there are 09 continents and 195 countries."
let ranges = string.ranges(of: "[0-9]+", options: .regularExpression)
因此,例如,如果您想在某些属性字符串中将这些数字加粗:
string.ranges(of: "[0-9]+", options: .regularExpression)
.map { NSRange($0, in: string) }
.forEach {
attributedString.setAttributes(boldAttributes, range: $0)
}