bremmm bremmm - 1 year ago 124
Swift Question

Swift: Separate String into String Array and Append Separator

How would I split a string to include the separators?

Lets say I had a string such as...

let myString = "apple banana orange grapes"

If I used

let separatedString = myString.componentsSeparatedByString(" ")

my resulting array would be


How would I achieve a result of

["apple ","banana ","orange ","grapes"]

Answer Source

Alternative using regular expression:

let myString = "apple banana orange grapes"
let pattern = "\\w+\\s?"
let regex  = try! NSRegularExpression(pattern: pattern, options: [])
let matches = regex.matchesInString(myString, options:[], range: NSMakeRange(0, myString.characters.count))
  .map { (myString as NSString).substringWithRange($0.range)}
print(matches) // -> ["apple ", "banana ", "orange ", "grapes"]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download