I imported a NSAttributedString from a rtf-file and now I want to split it at another given String. With the attributedSubstring
method you get one attributedSubstring as result, but I want to split it at every part, where the other String appeares, so the result should be an Array of NSAttributedStrings. Example:
var source = NSAttributedString(string: "I*** code*** with*** swift") var splitter = "***" var array = //The method I am looking for
The result should be the following Array(with attributedStrings): [I, code, with, swift]
Following extension method maps the string components using Array.map
into [NSAttributedString]
extension NSAttributedString {
func components(separatedBy string: String) -> [NSAttributedString] {
var pos = 0
return self.string.components(separatedBy: string).map {
let range = NSRange(location: pos, length: $0.count)
pos += range.length + string.count
return self.attributedSubstring(from: range)
}
}
}
Usage
let array = NSAttributedString(string: "I*** code*** with*** swift").components(separatedBy: "***")
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.