Replacing Substrings
Part of the Logic & Flow section of Coddy's Swift journey — lesson 5 of 56.
replacingOccurrences(of:with:) returns a new string with every match of one substring replaced by another:
let phone = "555-123-4567"
let digits = phone.replacingOccurrences(of: "-", with: "")
print(digits) // "5551234567"Like the case methods, it returns a new String; the original is untouched. Chain calls when you need to remove several patterns:
let messy = " 555-123 4567 "
let clean = messy
.replacingOccurrences(of: "-", with: "")
.replacingOccurrences(of: " ", with: "")
print(clean) // "5551234567"Two replacements means two passes over the string. For performance-sensitive code on huge strings, prefer a single filter pass over the characters; for everyday work, chained replacements are fine and read clearly.
Challenge
BeginnerRead a single line of input. Treat it as a sentence and produce a slug suitable for a URL by:
- Lower-casing the input
- Replacing every space with a
- - Removing every
!,?, and.character
Print the resulting slug.
For input Hello World!, the output is hello-world. For Is Swift Fun?, the output is is-swift-fun.
Cheat sheet
replacingOccurrences(of:with:) returns a new string with every match replaced:
let digits = "555-123-4567".replacingOccurrences(of: "-", with: "")
// "5551234567"Chain calls to handle multiple patterns:
let clean = "555-123 4567"
.replacingOccurrences(of: "-", with: "")
.replacingOccurrences(of: " ", with: "")Try it yourself
let line = readLine()!
// TODO: lowercase, swap spaces for hyphens, drop ! ? . characters
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