How to split a string by new lines in Swift

后端 未结 9 2315
一个人的身影
一个人的身影 2020-11-29 06:59

I have a string that I got from a text file.

Text file:

Line 1
Line 2
Line 3
...

I want to convert it to an array, one array element p

相关标签:
9条回答
  • 2020-11-29 07:55

    Swift 4:

    I would recommend to first save your CSV into string if you haven't already done it, then "clean" the string by removing unnecessary carriage returns

            let dataString = String(data: yourData!, encoding: .utf8)!
    
            var cleanFile = dataString.replacingOccurrences(of: "\r", with: "\n")
            cleanFile = cleanFile.replacingOccurrences(of: "\n\n", with: "\n")
    

    Above will give you a string with a most desirable format, then you can separate the string using \n as your separator:

            let csvStrings = cleanFile.components(separatedBy: ["\n"])
    

    Now you have an array of 3 items like:

    ["Line1","Line2","Line3"]

    I am using a CSV file and after doing this, I am splitting items into components, so if your items were something like:

    ["Line1,Line2,Line3","LineA,LineB,LineC"]

            let component0 = csvStrings[0].components(separatedBy: [","]) // ["Line1","Line2","Line3"]
            let component1 = csvStrings[1].components(separatedBy: [","]) // ["LineA","LineB","LineC"]
    
    0 讨论(0)
  • 2020-11-29 07:56

    in Xcode 8.2, Swift 3.0.1:

    Use NSString method components(separatedBy:)

    let text = "line1\nline2"
    let array = text.components(separatedBy: CharacterSet.newlines)
    

    Or use String method enumerateLines, like Leo Dabus's answer

    0 讨论(0)
  • 2020-11-29 07:57
    let test1 = "Line1\n\rLine2\nLine3\rLine4"
    let t1 = test1.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())
    let t2 = t1.filter{ $0 != "" }
    let t3 = t1.filter{ !$0.isEmpty }
    
    0 讨论(0)
提交回复
热议问题