How to get a table of paragraph words in Swift?

advertisements

If I have some sentences like the ones below,

"Hello everyone. This is a sentence."

how can I use Swift to get an array like this

var words = ["Hello", "everyone", "This", "is", "a", "sentence"]

I would also need a way of being able to remember where each word is in the original string, and where full stops and commas were. So that if I were to make this array of words back into the same string, it would read

"Hello everyone. This is a sentence."

Thanks!


Substrings broken down by word is built right in to Cocoa:

let s = "Hello everyone. This is a sentence."
var arr = [String]()
s.enumerateSubstringsInRange(s.startIndex..<s.endIndex, options: .ByWords) {
    ss, r, r2, stop in
    arr.append(ss)
}
// now arr is ["Hello", "everyone", "This", "is", "a", "sentence"]

(But the rest of your spec makes no sense to me, so I omitted it. You can see how to work out where the words come from, since the two ranges r and r2 tell you all about it.)