【问题标题】:Splitting String using CharacterSet使用 CharacterSet 分割字符串
【发布时间】:2016-11-09 11:08:06
【问题描述】:

在 Swift 2.x 中我能够做到:

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)

但在 Swift 3.x 中它发生了变化。谁能告诉我如何在 Swift 3 中使用它?

【问题讨论】:

    标签: swift string swift3


    【解决方案1】:

    这在 Swift 3 中变得更简单了。

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

    或者干脆

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

    【讨论】:

      【解决方案2】:

      @jjatie 给出的答案是正确的,但它还会在 Array 中包含空的 String 元素,您可以使用 filter 简单地删除空的 String 元素。

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

      【讨论】:

        猜你喜欢
        • 2011-03-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-16
        相关资源
        最近更新 更多