[SOLVED] Split String into Array keeping delimiter/separator in Swift

Issue

Looking for an (elegant) solution for splitting a string and keeping the separator as item(s) in the array

example 1:

"hello world"

["hello", " ", "world"]

example 2:

" hello world"

[" ", "hello", " ", "world"]

thx.

Solution

Suppose you are splitting the string by a separator called separator, you can do the following:

let result = yourString.components(separatedBy:  separator) // first split
                        .flatMap { [$0, separator] } // add the separator after each split
                        .dropLast() // remove the last separator added
                        .filter { $0 != "" } // remove empty strings

For example:

let result = " Hello World ".components(separatedBy:  " ").flatMap { [$0, " "] }.dropLast().filter { $0 != "" }
print(result) // [" ", "Hello", " ", "World", " "]

Answered By – Sweeper

Answer Checked By – David Marino (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *