bremmm bremmm - 3 months ago 6x
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"]


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