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

fet*_*zig 3 string swift

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

示例 1:

"hello world"

["hello", " ", "world"]
Run Code Online (Sandbox Code Playgroud)

例子2:

" hello world"

[" ", "hello", " ", "world"]
Run Code Online (Sandbox Code Playgroud)

谢谢。

Swe*_*per 7

假设您通过名为 的分隔符拆分字符串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
Run Code Online (Sandbox Code Playgroud)

例如:

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