Reputation: 514
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)
}
}
Upvotes: 0
Views: 168
Reputation: 285059
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)
inRange
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])
}
}
Upvotes: 1