In Swift, you can replace part of a string using the replacingOccurrences(of:with:) method:
s.replacingOccurrences(of: old, with: new) // replaces all occurrences
s.replacingOccurrences(of: pattern, with: new,
options: .regularExpression) // replaces using a regex pattern
Here are some examples:
let sentence = "I love cats"
let result = sentence.replacingOccurrences(of: "cats", with: "dogs")
print(result) // "I love dogs"
let text = "aaa"
print(text.replacingOccurrences(of: "a", with: "b")) // "bbb"
replacingOccurrences(of:with:) returns a new String — the original is not modified.
Assignment
Follow the Coding Tutorial and replace "cats" with "dogs" in sentence!
Hint
Use sentence.replacingOccurrences(of: "cats", with: "dogs") and assign it to result.
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check