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

后端 未结 6 2065
情歌与酒
情歌与酒 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:19

    String has a enumerateSubstringsInRange() method. With the .ByWords option, it detects word boundaries and punctuation automatically:

    Swift 3/4:

    let string = "Hello, this : is .. a \"string\"!"
    var words : [String] = []
    string.enumerateSubstrings(in: string.startIndex.. () in
                                        words.append(substring!)
    }
    print(words) // [Hello, this, is, a, string]
    

    Swift 2:

    let string = "Hello, this : is .. a \"string\"!"
    var words : [String] = []
    string.enumerateSubstringsInRange(string.characters.indices,
        options: .ByWords) {
            (substring, _, _, _) -> () in
            words.append(substring!)
    }
    print(words) // [Hello, this, is, a, string]
    

提交回复
热议问题