7

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

for instance:

var str = "Hello, Playground!"

to:

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

Thank you :)

1

4 Answers 4

8

edit/update:

Xcode 10.2 • Swift 5 or later

We can extend StringProtocol using collection split method

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

setting omittingEmptySubsequences to true and passing a closure as predicate. We can also take advantage of the new Character property isLetter to split the string.

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

let sentence = "• Hello, Playground!"
let words = sentence.words // ["Hello", "Playground"]
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1

That last solution (from Leo) will create empty elements in the array when there are multiple consecutive spaces in the string. It will also combine words separated by "-" and process end of line characters as words.

This one won't :

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

Comments

-1

To add each word of a sentence into a Set in Swift, you can use the components(separatedBy:) method to split the sentence into words and then insert each word into the Set.

Here’s an example:

Implementation:

func wordsToSet(sentence: String) -> Set<String> {
    // Split the sentence into words by spaces
    let words = sentence.components(separatedBy: " ")
    
    // Create a Set from the array of words
    let wordSet = Set(words)
    
    return wordSet
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.