Arefly Arefly - 1 year ago 291
iOS Question

componentsseparatedbystring by multiple separators in Swift

So here is the string


"Hi! How are you? I'm fine. It is 6 p.m. Thank you! That's it."

I want them to be separated to a array as:

["Hi", "How are you", "I'm fine", "It is 6 p.m", "Thank you", "That's it"]

Which means the separators should be
". "
"? "
"! "

I've tried:

let charSet = NSCharacterSet(charactersInString: ".?!")
let array = s.componentsSeparatedByCharactersInSet(charSet)

But it will separate
to two elements too. Result:

["Hi", " How are you", " I'm fine", " It is 6 p", "m", " Thank you", " That's it"]

I've also tried

let array = s.componentsSeparatedByString(". ")

It works well for separating
". "
but if I also want to separate
"? "
"! "
, it become messy.

So any way I can do it? Thanks!

Answer Source

There is a method provided that lets you enumerate a string. You can do so by words or sentences or other options. No need for regular expressions.

let s = "Hi! How are you? I'm fine. It is 6 p.m. Thank you! That's it."
var sentences = [String]()
s.enumerateSubstringsInRange(s.startIndex..<s.endIndex, options: .BySentences) { 
    substring, substringRange, enclosingRange, stop in

The result is:

["Hi! ", "How are you? ", "I\'m fine. ", "It is 6 p.m. ", "Thank you! ", "That\'s it."]

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download