How can I put each word of a string into an array in Swift?

后端 未结 3 708
清歌不尽
清歌不尽 2020-12-19 06:05

Is it possible to put each word of a string into an array in Swift?

for instance:

var str = \"Hello, Playground!\"

to:



        
3条回答
  •  别那么骄傲
    2020-12-19 06:29

    Neither answer currently works with Swift 4, but the following can cover OP's issue & hopefully yours.

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

    And with a longer phrase with numbers and a double space:

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

提交回复
热议问题