gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 06:11:46 26 4
gpt4 key购买 nike

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

示例 1:

"hello world"

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

示例 2:

" hello world"

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

谢谢。

最佳答案

假设您要使用名为 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", " "]

关于swift - 将字符串拆分为数组,在 Swift 中保留定界符/分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54870296/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com