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

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

    An alternate way to filter characters from a set and obtain an array of words is by using the array's filter and reduce methods. It's not as compact as other answers, but it shows how the same result can be obtained in a different way.

    First define an array of the characters to remove:

    let charactersToRemove = Set(Array(".:?,"))
    

    next convert the input string into an array of characters:

    let arrayOfChars = Array(words)
    

    Now we can use reduce to build a string, obtained by appending the elements from arrayOfChars, but skipping all the ones included in charactersToRemove:

    let filteredString = arrayOfChars.reduce("") {
        let str = String($1)
        return $0 + (charactersToRemove.contains($1) ? "" : str)
    }
    

    This produces a string without the punctuation characters (as defined in charactersToRemove).

    The last 2 steps:

    split the string into an array of words, using the blank character as separator:

    let arrayOfWords = filteredString.componentsSeparatedByString(" ")
    

    last, remove all empty elements:

    let finalArrayOfWords = arrayOfWords.filter { $0.isEmpty == false }
    

提交回复
热议问题