如何从使用nsrange的emoj的字符串中获取部分内容

loading...


0

我有一些表情符号的字符串,现在我想使用nsrange获取子字符串,我有位置和长度

我遇到了问题,因为表情符号需要2个位置,如果没有表情符号我正在使用子字符串和使用下面代码的范围

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)
    }
}

loading...

1回答

  • 0

    不要使用 NSRange 来获取Swift中的子串 .

    有两个便利API可以将 NSRange 转换为 Range<String.Index> ,反之亦然

    739 init?(_ range: NSRange, in string: String) in Range

    • NSRange(_ range: Range<String.Index>, in string: StringProtocol) in 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])
        }
    }
    
评论

暂时没有评论!