Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

macos

ios

swift

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 have something like

var words = "Hello, this : is .. a  string?"

I would like to be able to create an array with

"[Hello, this, is, a, string]"

My original thought was to use something like words.stringByTrimmingCharactersInSet() to remove any characters I didn't want but that would only take characters off the ends.

I thought maybe I could iterate through the string with something in the vein of

for letter in words {
    if NSCharacterSet.punctuationCharacterSet.characterIsMember(letter){
        //remove that character from the string
    }
}

but I'm unsure how to remove the character from the string. I'm sure there are some problems with the way that if statement is set up, as well, but it shows my thought process.

like image 316
qmlowery Avatar asked Apr 16 '15 06:04

qmlowery


1 Answers

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

 
like image 57
Leo Dabus Avatar answered Sep 18 '22 21:09

Leo Dabus