gpt4 book ai didi

ios - componentsseparatedbystring 在 Swift 中由多个分隔符

转载 作者:搜寻专家 更新时间:2023-10-31 21:57:57 25 4
gpt4 key购买 nike

所以这里是字符串s:

"Hi! How are you? I'm fine. It is 6 p.m. Thank you! That's it."

我希望将它们分隔成一个数组:

["Hi", "How are you", "I'm fine", "It is 6 p.m", "Thank you", "That's it"]

这意味着分隔符应该是 ". " + "? " + "! "

我试过:

let charSet = NSCharacterSet(charactersInString: ".?!")
let array = s.componentsSeparatedByCharactersInSet(charSet)

但它也会将 p.m. 分成两个元素。结果:

["Hi", " How are you", " I'm fine", " It is 6 p", "m", " Thank you", " That's it"]

我也试过

let array = s.componentsSeparatedByString(". ")

它很适合分隔 "." 但如果我还想分隔 "?", "!", 它会变得困惑.

那么我有什么办法可以做到吗?谢谢!

最佳答案

提供了一种方法,可让您枚举字符串。您可以通过单词或句子或其他选项来做到这一点。不需要正则表达式。

let s = "Hi! How are you? I'm fine. It is 6 p.m. Thank you! That's it."
var sentences = [String]()
s.enumerateSubstringsInRange(s.startIndex..<s.endIndex, options: .BySentences) {
substring, substringRange, enclosingRange, stop in
sentences.append(substring!)
}
print(sentences)

结果是:

["Hi! ", "How are you? ", "I\'m fine. ", "It is 6 p.m. ", "Thank you! ", "That\'s it."]

关于ios - componentsseparatedbystring 在 Swift 中由多个分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34247316/

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