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:andwith:.
Key takeaways
replacingOccurrences(of:with:)replaces all matches and returns a newString.- It is case-sensitive unless you pass
options: .caseInsensitive. - It needs Foundation.
replacing(_:with:)works without it.
