Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 950
He Yifei 何一非 Avatar asked Dec 19 '22 21:12

He Yifei 何一非


1 Answers

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

like image 115
rmaddy Avatar answered Dec 21 '22 09:12

rmaddy