当前位置:  开发笔记 > 编程语言 > 正文

components由Swift中的多个分隔符分隔

如何解决《components由Swift中的多个分隔符分隔》经验,为你挑选了1个好方法。

所以这是字符串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(". ")

它可以很好地用于分离". ",但如果我也想分开"? ","! ",它变得杂乱.

所以我能做到这一点吗?谢谢!



1> rmaddy..:

提供了一种允许枚举字符串的方法.您可以通过单词或句子或其他选项来完成此操作.不需要正则表达式.

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点","谢谢!","就是这样."]

推荐阅读
李桂平2402851397
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有