Start learning free

LESSON 64 OF 678 · STRINGS I

String Split in Swift

Lesson

In Swift, you can split a string into an array of substrings using split(separator:). It takes a character (or a string) as the delimiter, and returns an array of Substring values:

s.split(separator: delimiter)   // splits using a delimiter

Here are some examples:

let sentence = "hello world foo"
let words = sentence.split(separator: " ")
// words == ["hello", "world", "foo"]

let csv = "a,b,c"
let parts = csv.split(separator: ",")
// parts == ["a", "b", "c"]

You can loop through the resulting array:

for w in words {
    print(w)
}

Assignment
Follow the Coding Tutorial and split sentence into an array of words!


Hint
Use sentence.split(separator: " ") and assign the result to words.

STEP 1 OF 1
    Ctrl + Enter to check