J'essaie de trouver NSRange
de plusieurs chaînes dans une chaîne.Recherche des occurrences de chaîne comme NSRange à partir d'un NSString en utilisant Swift, résultat NSRange à utiliser dans NSAttributedString
Dans mon code suivant, j'utilise la méthode String.range(of: String, options: , Range)
pour trouver Range
et le convertir en NSRange
. cette conversion échoue lorsque le texte contient l'unité multi-codes de caractères unicode, comme emoji:
let findInString = "This #is a #tag #tag inten#sive#search" // MAY CONTAINS EMOJIS
let findStrings = ["#is","#tag","#sive","#search"]
let result = NSMutableAttributedString(string: findInString)
for (index, stringToFind) in findStrings.enumerated() {
var nextStartIndex = findInString.startIndex
while let range = findInString.range(of: stringToFind, options: [.literal, .caseInsensitive], range: nextStartIndex..<findInString.endIndex) {
let start = findInString.distance(from: findInString.startIndex, to: range.lowerBound)
let length = findInString.distance(from: range.lowerBound, to: range.upperBound)
result.addAttribute(NSLinkAttributeName, value: "\(index):", range: NSMakeRange(start, length))
nextStartIndex = range.upperBound
}
}
Question: Est-il travailler Si je NSString.range()
pour trouver NSRange
. J'essaye ceci, mais mon code suivant ont une erreur dans la partie range:
.
let findInNsString = findInString as NSString
while let range = findInNsString.range(of: stringToFind, options: [.literal, .caseInsensitive], range: nextStartIndex..<findInString.endIndex)
J'ai besoin d'aide pour comprendre et corriger l'erreur ci-dessus, merci d'avance.