gpt4 book ai didi

swift - 基于多个字符串定界符拆分字符串的高效算法

转载 作者:行者123 更新时间:2023-12-05 09:35:06 24 4
gpt4 key购买 nike

我想知道是否有一种有效的方法可以根据也是字符串的分隔符将字符串拆分为多个字符串。例如。 updateStr = "23+45 = 56 0", 分隔符 = ["+","","="]

结果 = [23,45,56,0]

我在 swift 中尝试了以下代码:

for i in 0..<delimiter.count {
let res = updateStr.components(separatedBy: delimiter[i])
updateStr = res.joined(separator: "unique%")
}
splitTxt = updateStr.components(separatedBy: "unique%")

这可行,但由于分隔符将被动态接收,我想要一个更好的方法。有什么有效的方法可以避免多次循环来解决这个问题吗?具有不涉及快速实例方法的更有效解决方案的算法也将受到赞赏。感谢您的回答,但是

更清楚一点,我不仅想要字符,还想要字符串作为分隔符:

例如 2。 updateStr = "我喜欢和 friend 一起玩", delimiters = ["li",""la","ie"]

Result = ["I ","ke p","ying with fr","nds"]

最佳答案

做这类事情的有效方法是使用集合:

let equation = "23+45 = 56 0"
let delimiters : [Character] = ["+"," ","="]
let setOfSeparators = Set(delimiters)
let result = equation.split {setOfSeparators.contains($0)}
print(result)

这很有效,因为 Set 上的 contains 非常快,因此成本可以忽略不计,我们只隐式循环一次原始字符串。

另一方面,您可以利用 Cocoa CharacterSet 类。为此,我会说:

let equation = "23+45 = 56 0"
let delimiters = ["+"," ","="]
let characterSet = CharacterSet(charactersIn: delimiters.joined())
let result = equation.components(separatedBy: characterSet).filter {!$0.isEmpty}
print(result)

另一种有趣的方式是使用扫描仪(在我看来这些都没有得到充分利用):

let equation = "23+45 = 56 0"
let delimiters = ["+"," ","="]
let characterSet = CharacterSet(charactersIn: delimiters.joined())
let scanner = Scanner(string: equation)
var result = [String]()
while let word = scanner.scanUpToCharacters(from: characterSet) {
result.append(word)
scanner.scanCharacters(from: characterSet)
}
print(result)

关于swift - 基于多个字符串定界符拆分字符串的高效算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66093582/

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