kfmfe04
kfmfe04

Reputation: 15327

How do I break a string into an array based on a token?

Background

For example, suppose I have:

let tgt     = "Europa"
let token   = "ro"
let a       = split_on( tgt, token )    // how to implement this?
let exp_res = [ "Eu", "ro", "pa" ]

I considered using String.componentsSeparatedByString but the split positions are lost (i.e. we do not know if the token appeared at the beginning, end, or if it occurred multiple times in a row.

Edit: Additional Examples

split_on( "roroEuropa", "ro" ) // [ "ro", "ro", "Eu", "ro", "pa" ]
split_on( "rorEuropa",  "ro" ) // [ "ro", "rEu", "ro", "pa" ]
split_on( "Euroroparo", "ro" ) // [ "Eu", "ro", "ro", "pa", "ro" ]

Upvotes: 0

Views: 87

Answers (1)

Martin R
Martin R

Reputation: 539695

This would be a possible solution. You could write it in a single line, but I have split it into separate statements to demonstrate how it works:

let tgt     = "roEuroroparo"
let token   = "ro"

// Split into an array of strings:
let t1 = tgt.componentsSeparatedByString(token)
println(t1)                   // [, Eu, , pa, ]

// Convert each string to an array:
let t2 = map(t1) { [$0] }
println(t2)                   // [[], [Eu], [], [pa], []]

// Interpose the token:
let t3 = [token].join(t2)
println(t3)                   // [, ro, Eu, ro, , ro, pa, ro, ]

// Remove empty strings:
let result = filter(t3) { countElements($0) > 0 }
println(result)               // [ro, Eu, ro, ro, pa, ro]

Upvotes: 1

Related Questions