我有一个包含emoji的文本,我必须使用Nsrange获取子字符串。
因为emoji,我没有得到子字符串,我使用下面的代码来查找子字符串,当emoji不存在时,它可以正常工作。请快速回答。

    extension String {
    //for finding the range
    func nsRanges(ofWord word: String) -> [NSRange] {
        var ranges: [NSRange] = []
        self.enumerateSubstrings(in: startIndex..., options: .byWords) {
            (substring, range, _, _) in

            let subrange = NSRange(range, in: self)

            let othersubstring = self.substring(location: subrange.location, length: word.count + 1)
           if othersubstring != nil{
                if othersubstring!  == word + " " {
                    ranges.append(NSRange(location: subrange.location, length: word.count))

                }
            }
        }
        return ranges
    }
    //for substring *emphasized text*
    func substring(location: Int, length: Int) -> String? {
        guard self.utf16.count >= location + length else {

            return nil
        }
        let start = index(startIndex, offsetBy: location)
        let end = index(startIndex, offsetBy: location + length)
        return substring(with: start..<end)
    }
}

最佳答案

不要使用NSRange在Swift中获取子字符串。
有两种方便的API可将NSRange转换为Range<String.Index>或反之亦然
init?(_ range: NSRange, in string: String)中的Range
NSRange(_ range: Range<String.Index>, in string: StringProtocol)中的NSRange
例如,将第二个函数替换为

extension String {

    func substring(location: Int, length: Int) -> String? {
        let nsRange = NSRange(location: location, length: length)
        guard let range = Range(nsRange, in: self) else { return nil }
        return String(self[range])
    }
}

关于ios - 如何使用nsrange从具有emoj的字符串中获取某些部分,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53703889/

10-13 03:51