0

I want a good way for seperating lines inside a huge string. I searched and found this article: https://medium.com/@sorenlind/three-ways-to-enumerate-the-words-in-a-string-using-swift-7da5504f0062

Base on this article I want use CFStringTokenizer. So I changed kCFStringTokenizerUnitWord to kCFStringTokenizerUnitLineBreak and finally I use this code:

func tokenize(_ str:String) -> [String] {
    var inputRange = CFRangeMake(0, str.count)
    var flag = UInt(kCFStringTokenizerUnitLineBreak)
    var locale = CFLocaleCopyCurrent()
    var tokenizer = CFStringTokenizerCreate(kCFAllocatorDefault, str as CFString, inputRange, flag, locale)
    var tokenType = CFStringTokenizerAdvanceToNextToken(tokenizer)


    while tokenType != []
    {
        var currentTokenRange = CFStringTokenizerGetCurrentTokenRange(tokenizer)
        var substring = substringWithRange(str, aRange: currentTokenRange)
        tokens.append(substring)
        tokenType = CFStringTokenizerAdvanceToNextToken(tokenizer)
    }

    return tokens
}

But It return me seperated words not seperated lines. What is the problem? Or If another way(good performance) you can suggest. Thanks.

Mohammad Eslami
  • 536
  • 1
  • 6
  • 17
  • Can you show your string? How are you defining line break in string? What is your purpose of separating into lines? – Kamran Jul 19 '18 at 11:59
  • "\r\na string of beads\r\nیک رشته مهره\r\n\r\na ball of string\r\nیک کلاف کاموا\r\n\r\na pile of books\r\nیک دسته کتاب\r\n\r\na bundle of news papers\r\nیک دسته روزنامه\r\n\r\na crowd of people\r\nیک جمعیت مردم" – Mohammad Eslami Jul 19 '18 at 13:13
  • so you just need to do this `let lineStrings = str.split(separator: "\n").map({ String($0) })` – Kamran Jul 19 '18 at 13:16
  • I need seperating because of this need: I want assign entire text to a multi line UILabel. I need each line in this text has it's alignment based on it's language(RTL or LTR). I want set alignment for each line text as NSAttributedString and concatenate them as a NSMutableAttributedString and assign it to attributedText property of UILabel. – Mohammad Eslami Jul 19 '18 at 13:18
  • I know that method. I want to show each of these huge texts inside UITableViewCell that scrollable. So performance is important. I don't want lag when scrolling. – Mohammad Eslami Jul 19 '18 at 14:38
  • Is there any issue while showing the text in tableview? If you prepared your data source and reloaded tableview then there will be no lag as tableview reuses that cell. – Kamran Jul 19 '18 at 15:53

0 Answers0