Start learning free

LESSON 63 OF 678 · STRINGS I

String Replace in Swift

Lesson

In Swift, you can replace part of a string using the replacingOccurrences(of:with:) method, which comes from Foundation, so a standalone file needs import Foundation at the top:

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:

import Foundation

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.

STEP 1 OF 1
    Ctrl + Enter to check