是否可以在Swift中将字符串的每个单词放入数组中?
例如:
var str = "Hello, Playground!"
至:
var arr = ["Hello","Playground"]
谢谢 :)
编辑/更新:
Xcode 10.2•Swift 5或更高版本
我们可以StringProtocol使用集合拆分方法进行扩展
StringProtocol
func split(maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, whereSeparator isSeparator: (Character) throws -> Bool) rethrows -> [Self.SubSequence]
设置omittingEmptySubsequences为true并通过闭包作为谓词。我们还可以利用new Character属性isLetter来分割字符串。
omittingEmptySubsequences
Character
isLetter
extension StringProtocol { var words: [SubSequence] { return split { !$0.isLetter } } }
let sentence = "• Hello, Playground!" let words = sentence.words // ["Hello", "Playground"]