Start learning free

LESSON 63 OF 415 · STRINGS I

String Replace in Swift: replacingOccurrences(of:with:)

Lesson Read the full explanation

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

    SWIFT · STRINGS I

    String Replace in Swift, explained

    Replacing text

    To swap one piece of text for another, call replacingOccurrences(of:with:). It replaces every occurrence of the first string with the second and returns the result. The method comes from Foundation, so a standalone file needs import Foundation at the top.

    import Foundation
    
    let sentence = "I love cats"
    let result = sentence.replacingOccurrences(of: "cats", with: "dogs")
    print(result)
    print(sentence)
    
    I love dogs
    I love cats
    

    The method doesn't change sentence. It returns a new string, which is why the result is stored in a second constant. If you want the variable itself to change, declare it with var and assign the result back:

    import Foundation
    
    var message = "I love cats"
    message = message.replacingOccurrences(of: "cats", with: "dogs")
    print(message)
    
    I love dogs
    

    All occurrences, not just the first

    Every match is replaced, and each character of the original is looked at once:

    import Foundation
    
    print("aaa".replacingOccurrences(of: "a", with: "b"))
    print("cats and cats".replacingOccurrences(of: "cats", with: "dogs"))
    print("abc".replacingOccurrences(of: "b", with: ""))
    print("I love cats".replacingOccurrences(of: "xyz", with: "q"))
    
    bbb
    dogs and dogs
    ac
    I love cats
    

    Replacing with an empty string removes the text. When nothing matches, you get the original string back unchanged.

    Options

    The method takes an optional options: argument. Matching is case-sensitive by default, and .caseInsensitive turns that off:

    import Foundation
    
    print("Cats".replacingOccurrences(of: "cats", with: "dogs"))
    print("Cats".replacingOccurrences(of: "cats", with: "dogs", options: .caseInsensitive))
    
    Cats
    dogs
    

    With .regularExpression, the first argument is read as a pattern instead of plain text:

    import Foundation
    
    print("a1b22c".replacingOccurrences(of: "[0-9]+", with: "#", options: .regularExpression))
    
    a#b#c
    

    Without that option, characters such as . are ordinary text: "a.b".replacingOccurrences(of: ".", with: "-") gives a-b.

    Chaining and overlapping matches

    Because each call returns a string, calls can be chained. Here spaces become hyphens, and the result is then converted to uppercase:

    import Foundation
    
    let title = "my first post"
    print(title.replacingOccurrences(of: " ", with: "-").uppercased())
    
    MY-FIRST-POST
    

    The search moves left to right and matches don't overlap. In "banana" the text "ana" occurs at positions 1 and 3, but the characters at position 3 are already used by the first match, so only one replacement happens:

    import Foundation
    
    print("banana".replacingOccurrences(of: "ana", with: "X"))
    print("aaaa".replacingOccurrences(of: "aa", with: "a"))
    
    bXna
    aa
    

    The replacement text is not searched again, so a single call can't keep shrinking "aaaa" down to one a.

    Removing characters

    Replacing with an empty string is the usual way to delete characters. Removing every space from a string is one call:

    import Foundation
    
    print("a b  c".replacingOccurrences(of: " ", with: ""))
    
    abc
    

    This removes spaces anywhere in the string. To remove only the spaces at the two ends, the trimming methods are the better tool. For one fixed piece of text, prefer the plain form of replacingOccurrences. Reach for .regularExpression only when the text you are looking for varies, such as any run of digits. In a pattern, characters such as +, ( and . have special meanings, so a plain search is safer whenever you want the text exactly as written.

    Without Foundation

    The standard library also has replacing(_:with:), which returns a new string, and the mutating replace(_:with:), which changes a var in place:

    let sentence = "I love cats"
    print(sentence.replacing("cats", with: "dogs"))
    
    var mutable = "I love cats"
    mutable.replace("cats", with: "dogs")
    print(mutable)
    
    I love dogs
    I love dogs
    

    The exercise

    The constant sentence holds "I love cats". Declare result with let and give it the sentence with "cats" replaced by "dogs". The print(result) line that follows then shows the new text.

            let sentence = "I love cats"
    
            let result = sentence.replacingOccurrences(of: "cats", with: "dogs")
            print(result)
    
    I love dogs
    

    Common mistakes

    • Expecting the original to change. The method returns a new string. Use the returned value.
    • Swapping the arguments. The text to find comes first (of:), the new text second (with:).
    • Ignoring case. A search for "cats" doesn't match "Cats" unless you pass .caseInsensitive.
    • Dropping the argument labels. Swift requires of: and with:.

    Key takeaways

    • replacingOccurrences(of:with:) replaces all matches and returns a new String.
    • It is case-sensitive unless you pass options: .caseInsensitive.
    • It needs Foundation. replacing(_:with:) works without it.
    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free