Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

substring with an array string - Swift

I have an array:

var array = ["1|First", "2|Second", "3|Third"]

How I can cut off "1|", "2|", "3|"?
The result should look like this:

println(newarray) //["First", "Second", "Third"]
like image 973
Сашок Гончаренко Avatar asked Jun 25 '15 07:06

Сашок Гончаренко


1 Answers

You can use (assuming the strings will contain the "|" character):

let newarray = array.map { $0.componentsSeparatedByString("|")[1] }

As @Grimxn pointed out, if you cannot assume that the "|" character will always be in the strings, use:

let newarray = array.map { $0.componentsSeparatedByString("|").last! }

or

let newarray2 = array.map { $0.substringFromIndex(advance(find($0, "|")!, 1)) }

result2 could be a little bit faster, because it doesn't create an intermediate array from componentsSeparatedByString.

or if you want to modify the original array:

for index in 0..<array.count {
    array[index] = array[index].substringFromIndex(advance(find(array[index], "|")!, 1))
}
like image 90
Dániel Nagy Avatar answered Sep 28 '22 12:09

Dániel Nagy