简体   繁体   中英

How to get the some part from string which has emoj using nsrange

I have text which has emoji in it,I have to get the substring using Nsrange.

I am not getting the substring because of emoji, I am using the below code to find the substring and it is working fine when emoji is not present. Thnaks for the quick answers.

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

Don't use NSRange to get substrings in Swift at all.

There are two convenience API's to convert NSRange to Range<String.Index> and vice versa

  • init?(_ range: NSRange, in string: String) in Range
  • NSRange(_ range: Range<String.Index>, in string: StringProtocol) in NSRange

For example replace the second function with

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM