如何将字符串中的每个单词放入Swift中的数组中?

时间:2015-01-09 22:36:25

标签: arrays string swift

是否可以将字符串中的每个单词放入Swift中的数组?

例如:

var str = "Hello, Playground!"

为:

var arr = ["Hello","Playground"]

谢谢:)

3 个答案:

答案 0 :(得分:7)

编辑/更新:

Xcode 10.2•Swift 5或更高版本

我们可以使用集合拆分方法扩展StringProtocol

func split(maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, whereSeparator isSeparator: (Character) throws -> Bool) rethrows -> [Self.SubSequence]

omittingEmptySubsequences设置为true并将闭包作为谓词传递。我们还可以利用新的Character属性isLetter来拆分字符串。

extension StringProtocol {
    var words: [SubSequence] {
        return split { !$0.isLetter }
    }
}

let sentence = "• Hello, Playground!"
let words = sentence.words // ["Hello", "Playground"]

答案 1 :(得分:1)

当字符串中有多个连续的空格时,最后一个解决方案(来自Leo)将在数组中创建空元素。它还会将以“ - ”分隔的单词和处理行尾字符组合为单词。

这个不会:

extension String 
{    
    var wordList: [String] 
    {
       return componentsSeparatedByCharactersInSet(NSCharacterSet.alphanumericCharacterSet().invertedSet).filter({$0 != ""})
    }
}

答案 2 :(得分:0)

这两个答案目前都不适用于Swift 4,但以下内容可以涵盖OP的问题&希望你的。

extension String {
    var wordList: [String] {
        return components(separatedBy: CharacterSet.alphanumerics.inverted).filter { !$0.isEmpty }
    }
}

let string = "Hello, Playground!"
let stringArray = string.wordList
print(stringArray) // ["Hello", "Playground"]

使用带有数字和双倍空格的较长短语:

let biggerString = "Hello, Playground! This is a  very long sentence with 123 and other stuff in it"
let biggerStringArray = biggerString.wordList
print(biggerStringArray)
// ["Hello", "Playground", "This", "is", "a", "very", "long", "sentence", "with", "123", "and", "other", "stuff", "in", "it"]