我有一些表情符号的字符串,现在我想使用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)
}
}
1 回答
不要使用
NSRange
来获取Swift中的子串 .有两个便利API可以将
NSRange
转换为Range<String.Index>
,反之亦然739
init?(_ range: NSRange, in string: String)
inRange
NSRange(_ range: Range<String.Index>, in string: StringProtocol)
inNSRange
例如,用第二个函数替换