Splitting and Joining
Part of the Logic & Flow section of Coddy's Swift journey — lesson 4 of 56.
Two everyday tools for working with delimited text. Both come from Foundation, which is already imported.
components(separatedBy:) breaks a string into an array of Strings on whatever delimiter you pass:
let csv = "red,green,blue"
let parts = csv.components(separatedBy: ",")
print(parts) // ["red", "green", "blue"]The reverse is joined(separator:) on any [String]:
let words = ["swift", "is", "fun"]
let line = words.joined(separator: " ")
print(line) // "swift is fun"You'll often combine them: split, transform with map, join back together. The result of map on a [String] is still a [String], so joined works directly.
Challenge
EasyRead a single line of input: a comma-separated list of words.
Print three lines:
- The number of words after splitting on
, - The words rejoined with
>(space, greater-than, space), in upper case - The longest word from the list (after splitting). If two words tie, use the one that appears first.
For input red,green,blue, the output is:
3
RED > GREEN > BLUE
greenCheat sheet
Split a string into an array using components(separatedBy:):
let parts = "red,green,blue".components(separatedBy: ",")
// ["red", "green", "blue"]Rejoin an array of strings using joined(separator:):
let line = ["swift", "is", "fun"].joined(separator: " ")
// "swift is fun"Common pattern — split, transform with map, rejoin:
let result = "red,green,blue"
.components(separatedBy: ",")
.map { $0.uppercased() }
.joined(separator: " > ")
// "RED > GREEN > BLUE"Try it yourself
let line = readLine()!
let words = line.components(separatedBy: ",")
// TODO: print count, joined-uppercased with " > ", first longest word
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
Count and IndicesCase and TrimSearching in StringsSplitting and JoiningReplacing SubstringsRecap - Username Check