所以这是字符串s
:
"Hi! How are you? I'm fine. It is 6 p.m. Thank you! That's it."
我希望它们被分隔为一个数组:
["Hi", "How are you", "I'm fine", "It is 6 p.m", "Thank you", "That's it"]
这意味着分隔符应为". "
+ "? "
+"! "
我试过了:
let charSet = NSCharacterSet(charactersInString: ".?!") let array = s.componentsSeparatedByCharactersInSet(charSet)
但它也将分为p.m.
两个元素.结果:
["Hi", " How are you", " I'm fine", " It is 6 p", "m", " Thank you", " That's it"]
我也试过了
let array = s.componentsSeparatedByString(". ")
它可以很好地用于分离". "
,但如果我也想分开"? "
,"! "
,它变得杂乱.
所以我能做到这一点吗?谢谢!
提供了一种允许枚举字符串的方法.您可以通过单词或句子或其他选项来完成此操作.不需要正则表达式.
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..结果是:
["嗨!","你好吗?","我没事.","现在是下午6点","谢谢!","就是这样."]