将字符串拆分为数组,在Swift中保留定界符/分隔符

时间:2019-02-25 16:07:19

标签: swift string

寻找一种(优雅的)解决方案来拆分字符串并将分隔符保留为数组中的项

示例1:

"hello world"

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

示例2:

" hello world"

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

thx。

1 个答案:

答案 0 :(得分:2)

假设您要通过名为separator的分隔符来分割字符串,则可以执行以下操作:

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

例如:

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