如何使用 nsrange 从具有 emoj 的字符串中获取某些部分
How to get the some part from string which has emoj using nsrange
我有包含表情符号的文本,我必须使用 Nsrange 获取子字符串。
因为表情符号,我没有得到子字符串,我正在使用下面的代码来查找子字符串,当表情符号不存在时它工作正常。感谢快速回答。
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])
}
}
我有包含表情符号的文本,我必须使用 Nsrange 获取子字符串。
因为表情符号,我没有得到子字符串,我正在使用下面的代码来查找子字符串,当表情符号不存在时它工作正常。感谢快速回答。
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])
}
}