Arefly Arefly - 4 months ago 80
iOS Question

componentsseparatedbystring by multiple separators in Swift

So here is the string

s
:

"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
p.m.
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

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
    sentences.append(substring!)
}
print(sentences)

The result is:

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

Comments