Count the number of lines in a Swift String

后端 未结 3 1151
天涯浪人
天涯浪人 2021-01-14 10:15

After reading a medium sized file (about 500kByte) from a web-service I have a regular Swift String (lines) originally encoded in .isolatin1. Befor

3条回答
  •  离开以前
    2021-01-14 10:40

    If it's ok for you to use a Foundation method on an NSString, I suggest using

    enumerateLines(_ block: @escaping (String, UnsafeMutablePointer) -> Void)
    

    Here's an example:

    import Foundation
    
    let base = "Hello, playground\r\nhere too\r\nGalahad\r\n"
    let ns = base as NSString
    
    ns.enumerateLines { (str, _) in
        print(str)
    }
    

    It separates the lines properly, taking into account all linefeed types, such as "\r\n", "\n", etc:

    Hello, playground
    here too
    Galahad

    In my example I print the lines but it's trivial to count them instead, as you need to - my version is just for the demonstration.

提交回复
热议问题