[英]How to find Multiple NSRange for a string from full string iOS swift
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)
错误
有人有更好的解决方案吗?
另一种方法是定义扩展以返回范围数组,即[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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.