我有一个数组:
var array = ["1|First","2|Second","3|Third"]
我如何切断“1 |”,“2 |”,“3 |”?
结果应如下所示:
println(newarray) //["First","Second","Third"]
解决方法
你可以使用(假设字符串将包含“|”字符):
let newarray = array.map { $0.componentsSeparatedByString("|")[1] }
正如@Grimxn指出的,如果你不能假设“|”字符将始终在字符串中,使用:
let newarray = array.map { $0.componentsSeparatedByString("|").last! }
要么
let newarray2 = array.map { $0.substringFromIndex(advance(find($0,"|")!,1)) }
result2可能会快一点,因为它不会从componentsSeparatedByString创建一个中间数组.
或者如果要修改原始数组:
for index in 0..<array.count { array[index] = array[index].substringFromIndex(advance(find(array[index],1)) }