寻找一种(优雅的)解决方案来拆分字符串并将分隔符保留为数组中的项
示例1:
"hello world"
["hello", " ", "world"]
示例2:
" hello world"
[" ", "hello", " ", "world"]
thx。
答案 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", " "]