【问题标题】:How to split the string from an array of strings in swift如何在swift中从字符串数组中拆分字符串
【发布时间】:2018-07-26 11:24:26
【问题描述】:

我有一个array 喜欢:

dateTime = ["2018/06/25 05:32:30","2018/05/25 02:37","2018/04/25 05:32:50","2018/07/25 06:30:30"]

需要拆分字符串并得到响应:

time = ["05:32:30","02:37","05:32:50","06:30:30"]

谁能帮忙解决这个问题。

【问题讨论】:

  • 您能告诉我为什么您将我的答案更改为不接受吗?

标签: ios arrays swift string split


【解决方案1】:

你可以使用flatMap:

let dates = ["2018/06/25 05:32:30","2018/05/25 02:37","2018/04/25 05:32:50","2018/07/25 06:30:30"]
let times = dates.flatMap({ $0.split(separator: " ").last ?? nil })
print(times)
// prints: ["05:32:30", "02:37", "05:32:50", "06:30:30"]

【讨论】:

    【解决方案2】:

    使用以下解决方案从所有元素中获取时间。

    let dateTime = ["2018/06/25 05:32:30","2018/05/25 02:37","2018/04/25 05:32:50","2018/07/25 06:30:30"]  
    let array = dateTime.map { $0.components(separatedBy: " ")[1] }
     //["05:32:30", "02:37", "05:32:50", "06:30:30"]
    

    【讨论】:

    • 只是要注意,如果没有找到第二个元素,使用下标[1] 可能会导致空指针。这就是为什么flatMap 更好。检查我的答案。
    【解决方案3】:

    循环每个项目并使用拆分功能

    let times = dateTime.compactMap { $0.split(separator: " ").last }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-10
      • 1970-01-01
      • 2014-10-29
      • 2020-12-01
      相关资源
      最近更新 更多