How to split a string by newline in Swift

1 Answer

0 votes
import Foundation

/**
 * Splits a multi-line string into an array of individual lines.
 * Automatically handles cross-platform line endings (Unix LF, Windows CRLF, etc.).
 *
 * - Parameter text: The input multi-line string to be split.
 * - Returns: An array of Strings containing each individual line.
 */
func splitByNewline(text: String) -> [String] {
    // Guard clause: Return an empty array if the string is empty
    guard !text.isEmpty else { return [] }
    
    // .newlines handles \n, \r\n, and other unicode line separators seamlessly
    return text.components(separatedBy: .newlines)
}

// --- Example Usage ---

func main() {
    // Sample text containing mixed line endings (Unix LF, Windows CRLF, and an empty line)
    let multilineText = "Hello Swift!\nThis is line two.\r\n\nFinal line here."

    // Call the splitting function
    let resultLines = splitByNewline(text: multilineText)

    // Print out the parsed lines with their indices
    for (index, line) in resultLines.enumerated() {
        print("Line \(index + 1): '\(line)'")
    }
}

main()


/*
run:

Line 1: 'Hello Swift!'
Line 2: 'This is line two.'
Line 3: ''
Line 4: ''
Line 5: 'Final line here.'

*/

 



answered 5 hours ago by avibootz
...