9

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"]

1 Answer 1

10

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))
}
Sign up to request clarification or add additional context in comments.

4 Comments

Swift 1.2 syntax: map(array) { $0.componentsSeparatedByString("|")[1] } The answer is swift 2.0
actually, mine as well Swift 1.2
ops, my mistake. Swift 1.2 has map() as global function and array function as well
This solution will crash if the "|" doesn't exist. Try it with var array = ["1|First", "2|Second", "3|Third", "Fourth"]. Consider changing the solution to let newarray = array.map { $0.componentsSeparatedByString("|").last! }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.