如何从完整字符串iOS swift中找到字符串的多个NSRange [英] How to find Multiple NSRange for a string from full string iOS swift

查看:158
本文介绍了如何从完整字符串iOS swift中找到字符串的多个NSRange的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

let fullString = "Hello world, there are \(string(07)) continents and \(string(195)) countries."
let range = [NSMakeRange(24,2), NSMakeRange(40,3)]

需要在整个完整字符串中找到数字的 NSRange,并且两个数字可能相同.目前硬编码如上所示,消息可以是动态的,硬编码值会出现问题.

Need to find the NSRange for numbers in the entire full string and there is a possibility that both numbers can be same. Currently hard coding like shown above, the message can be dynamic where hard coding values will be problematic.

我已经拆分了字符串并尝试获取 NSRange 因为有可能是相同的值.像 stringOne 和 stringTwo.

I have split the strings and try to fetch NSRange since there is a possibility of same value. like stringOne and 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)
            }
        })
    }

接收错误,例如无法使用类型为 (String.Index, String.Index) 的参数列表调用距离

谁有更好的解决方案?

推荐答案

另一种方法是定义一个扩展来返回范围数组,即 [Range]:>

Another approach is to define an extension to return an array of ranges, i.e. [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
    }
}

然后你可以像这样使用它:

Then you can use it like so:

let string = "Hello world, there are 09 continents and 195 countries."
let ranges = string.ranges(of: "[0-9]+", options: .regularExpression)

因此,例如,如果您想在某些属性字符串中将这些数字设为粗体:

So, for example, if you wanted to make these numbers bold in some attributed string:

string.ranges(of: "[0-9]+", options: .regularExpression)
    .map { NSRange($0, in: string) }
    .forEach {
        attributedString.setAttributes(boldAttributes, range: $0)
}

这篇关于如何从完整字符串iOS swift中找到字符串的多个NSRange的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆