如何快速从字符串数组中拆分字符串

时间:2018-07-26 11:24:26

标签: ios arrays swift string split

我有一个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"]

有人可以帮忙吗?

3 个答案:

答案 0 :(得分: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 :(得分:2)

您可以使用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 :(得分:2)

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

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