【问题标题】:Isolating punctuation from words in Swift从 Swift 中的单词中分离标点符号
【发布时间】:2016-10-19 00:30:35
【问题描述】:

我正在尝试将 not remove 标点符号从数组中的单词中分离出来。

例如,这个数组包含带有标点符号的单词:

let words = ["hello", "world!!"]

下面的代码执行了一个标点符号的隔离。

for i in 0..<words.count {          
    if let range = words[i].rangeOfCharacter(from: .punctuationCharacters) {
        words.insert(words[i].substring(with: range), at: i+1)
        words[i].replaceSubrange(range, with: "")
    }
}

因此words 数组变为:

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

但是,我希望该功能可以单独隔离每个标点符号,而不是像现在这样一次一个:

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

截至目前,我已经尝试遍历字符串的字符并针对 CharacterSet.punctuationCharacters 进行测试,但这感觉效率低且笨拙

我怎样才能以 Swift-y 的方式实现这一点?

【问题讨论】:

    标签: arrays swift swift3 punctuation


    【解决方案1】:

    我不认为有一种 Swifty 时尚的方式来做到这一点,但如果你的单词数组是一致的,你可以这样做:

    let words = ["hello", "world!!"]
    var res: [String] = []
    for word in words {
        res += word.components(separatedBy: .punctuationCharacters).filter{!$0.isEmpty}
        res += word.components(separatedBy: CharacterSet.punctuationCharacters.inverted).filter{!$0.isEmpty}.joined().characters.map{String($0)}
    }
    print(res)   // ["hello", "world", "!", "!"]
    

    【讨论】:

      猜你喜欢
      • 2020-03-11
      • 2018-04-05
      • 1970-01-01
      • 1970-01-01
      • 2020-02-26
      • 1970-01-01
      • 1970-01-01
      • 2010-09-26
      相关资源
      最近更新 更多