Start learning free

LESSON 63 OF 349 · STRINGS I

String Split in Swift in Swift

Lesson

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

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

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 a String array!


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

STEP 1 OF 1
    Ctrl + Enter to check

    String Split in Swift

    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free