如何分割NSAttributedString

时间:2019-05-02 19:18:15

标签: swift split nsattributedstring

我从rtf文件导入了NSAttributedString,现在我想将其拆分为另一个给定的String。使用#include <assert.h> #include <threads.h> mtx_t mx_wakeup; cnd_t cd_wakeup, cd_complete; enum request { REQ_NOTHING, REQ_TERMINATE } request; int daemon(void *arg) { (void)arg; int retval; for(;;) { request = REQ_NOTHING; retval = cnd_wait(&cd_wakeup, &mx_wakeup); assert(retval == thrd_success); // The request can be processed here. // Inform the main thread that the request was completed. The main // thread can choose to wait or not. retval = cnd_signal(&cd_complete); assert(retval == thrd_success); // Termination is different because the mutex wouldn't be released // by the next `cnd_wait`, and must happend after the signal was send. if(request == REQ_TERMINATE) { retval = mtx_unlock(&mx_wakeup); assert(retval == thrd_success); return 0; } } } void send(enum request request_) { int retval; retval = mtx_lock(&mx_wakeup); assert(retval == thrd_success); request = request_; retval = cnd_signal(&cd_wakeup); assert(retval == thrd_success); // This unlocks the mutex thus allowing the worker thread to process the // request, thus the mutex can be reused here. retval = cnd_wait(&cd_complete, &mx_wakeup); assert(retval == thrd_success); retval = mtx_unlock(&mx_wakeup); assert(retval == thrd_success); } int main() { int retval; retval = mtx_init(&mx_wakeup, mtx_plain); assert(retval == thrd_success); retval = cnd_init(&cd_wakeup); assert(retval == thrd_success); // Remember to initialize the new conditional variable. retval = cnd_init(&cd_complete); assert(retval == thrd_success); retval = mtx_lock(&mx_wakeup); assert(retval == thrd_success); thrd_t thread; retval = thrd_create(&thread, daemon, NULL); assert(retval == thrd_success); send(REQ_TERMINATE); retval = thrd_join(thread, NULL); assert(retval == thrd_success); cnd_destroy(&cd_wakeup); mtx_destroy(&mx_wakeup); } 方法,您将得到一个attributedSubstring作为结果,但是我想在每个部分都将其拆分,另一个String出现在该部分,因此结果应为NSAttributedStrings数组。 示例:
attributedSubstring 结果应为以下Array(带有attributedStrings):[I,code,with,swift]

1 个答案:

答案 0 :(得分:1)

以下扩展方法将使用Array.map的字符串成分映射到[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)
        }
    }
}

用法

let array = NSAttributedString(string: "I*** code*** with*** swift").components(separatedBy: "***")