How can I remove or replace all punctuation characters from a String?

后端 未结 6 2053
情歌与酒
情歌与酒 2021-02-05 14:46

I have a string composed of words, some of which contain punctuation, which I would like to remove, but I have been unable to figure out how to do this.

For example if I

6条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-05 15:41

    Xcode 11.4 • Swift 5.2 or later

    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"]
    
     
    

提交回复
热议问题