07-18-2023, 11:30 PM
Update for Swift 5.2 and the simpliest way
let paragraph = "Bob hit a ball, the hit BALL flew far after it was hit. Hello! Hie, How r u?"
let words = paragraph.components(separatedBy: [",", " ", "!",".","?"])
This prints,
> ["Bob", "hit", "a", "ball", "", "the", "hit", "BALL", "flew", "far",
> "after", "it", "was", "hit", "", "Hello", "", "Hie", "", "How", "r",
> "u", ""]
However, if you want to filter out empty string,
let words = paragraph.components(separatedBy: [",", " ", "!",".","?"]).filter({!$0.isEmpty})
Output,
> ["Bob", "hit", "a", "ball", "the", "hit", "BALL", "flew", "far",
> "after", "it", "was", "hit", "Hello", "Hie", "How", "r", "u"]
But make sure, **Foundation** is imported.
let paragraph = "Bob hit a ball, the hit BALL flew far after it was hit. Hello! Hie, How r u?"
let words = paragraph.components(separatedBy: [",", " ", "!",".","?"])
This prints,
> ["Bob", "hit", "a", "ball", "", "the", "hit", "BALL", "flew", "far",
> "after", "it", "was", "hit", "", "Hello", "", "Hie", "", "How", "r",
> "u", ""]
However, if you want to filter out empty string,
let words = paragraph.components(separatedBy: [",", " ", "!",".","?"]).filter({!$0.isEmpty})
Output,
> ["Bob", "hit", "a", "ball", "the", "hit", "BALL", "flew", "far",
> "after", "it", "was", "hit", "Hello", "Hie", "How", "r", "u"]
But make sure, **Foundation** is imported.