Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
915 views
in Technique[技术] by (71.8m points)

arrays - How to split a string by new lines in Swift

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 Line 2 Line 3 ..." where is the new line (line feed) character

  • string = "Line 1 Line 2 Line 3 ..." where is the carriage return character.

As I understand it, is commonly used in Apple/Linux today, while 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.

See my summarized answer here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Swift 5.2 or later

You can split your String using the new Character property isNewline:

let sentence = "Line 1
Line 2
Line 3
"
let lines = sentence.split(whereSeparator: .isNewline)
print(lines)   // "["Line 1", "Line 2", "Line 3"]
"

You can also extend StringProtocol and create a lines instance property to break up the string lines into subsequences:

extension StringProtocol {
    var lines: [SubSequence] { split(whereSeparator: .isNewline) }
}

let sentence = "Line 1
Line 2
Line 3
"
for line in sentence.lines {
    print(line)
}
let lines = sentence.lines  // ["Line 1", "Line 2", "Line 3"]


Original Answer

You can use String method enumerateLines:

Enumerates all the lines in a string.

Swift 3 or later

let sentence = "Line 1
Line 2
Line 3
"
var lines: [String] = []
sentence.enumerateLines { line, _ in
    lines.append(line)
}
print(lines)   // "["Line 1", "Line 2", "Line 3"]
"

extension String {
    var lines: [String] {
        var result: [String] = []
        enumerateLines { line, _ in result.append(line) }
        return result
    }
}

let sentence2 = "Line 4
Line 5
Line 6
"
let sentence2Lines = sentence2.lines
print(sentence2Lines)    // "["Line 4", "Line 5", "Line 6"]
"
let sentence3 = "Line 7
Line 8
Line 9
"
let sentence3Lines = sentence3.lines
print(sentence3Lines)  // "["Line 7", "Line 8", "Line 9"]
"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...