我有一个由单词组成的字符串,其中一些包含标点符号,我想删除它们,但我一直不知道如何做到这一点。
例如,如果我有类似的东西
var words = "Hello, this : is .. a string?"
我希望能够创建一个数组
"[Hello, this, is, a, string]"
我最初的想法是使用类似的东西words.stringByTrimmingCharactersInSet()
删除任何我不想要的字符,但这只会从末尾删除字符。
我想也许我可以用以下方式迭代字符串
for letter in words {
if NSCharacterSet.punctuationCharacterSet.characterIsMember(letter){
//remove that character from the string
}
}
但我不确定如何从字符串中删除该字符。我确信 if 语句的设置方式也存在一些问题,但它显示了我的思维过程。
Xcode 11.4 • Swift 5.2 或更高版本
extension StringProtocol {
var words: [SubSequence] {
split(whereSeparator: \.isLetter.negation)
}
}
extension Bool {
var negation: Bool { !self }
}
let sentence = "Hello, this : is .. a string?"
let words = sentence.words // ["Hello", "this", "is", "a", "string"]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)