How to split a string by new lines in Swift

后端 未结 9 2475
一个人的身影
一个人的身影 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"]
    

提交回复
热议问题