Start learning free

LESSON 62 OF 349 · STRINGS I

String Replace in Swift in Swift

Lesson

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.

STEP 1 OF 1
    Ctrl + Enter to check

    String Replace 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