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 per line.
[ "Line 1", "Line 2", "Line 3", ... ]
Depending on how the file was saved, the string could take one of the following forms:
string = "Line 1\nLine 2\nLine 3\n..."
where\n
is the new line (line feed) characterstring = "Line 1\r\nLine 2\r\nLine 3\r\n..."
where\r
is the carriage return character.
As I understand it, \n
is commonly used in Apple/Linux today, while \r\n
is used in Windows.
How do I split a string at any line break to get a String array without any empty elements?
Update
There are several solutions that work below. At this point I don't have any compelling reason to choose one as more correct than the others. Some factors that may influence choice could be (1) how "Swift" it is and (2) how fast it is for very long strings. You can provide feedback by upvoting one or more of them and/or leaving a comment.