Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting String using CharacterSet

In Swift 2.x I was able to do:

let str = "Line 1\nLine 2\r\nLine 3\n"
let newlineChars = NSCharacterSet.newlineCharacterSet()
let lines = str.utf16.split { newlineChars.characterIsMember($0) }.flatMap(String.init)

But in Swift 3.x it has changed. Can someone tell me how to use this in Swift 3?

like image 225
Henny Lee Avatar asked Mar 18 '26 06:03

Henny Lee


1 Answers

This is a bit simpler in Swift 3 now.

let str = "Line 1\nLine 2\r\nLine 3\n"
let newlineChars = NSCharacterSet.newlines
let lines = str.components(separatedBy: newlineChars)
    .filter{ !$0.isEmpty }

or simply

let str = "Line 1\nLine 2\r\nLine 3\n"
let lines = str.components(separatedBy: .newlines)
    .filter{ !$0.isEmpty }
like image 113
jjatie Avatar answered Mar 19 '26 20:03

jjatie