Replacing and Finding Strings in Swift
In this article, we'll look at how to replace and find strings in Swift.
Replacing Strings
In Swift, you can replace parts of a string using the replacingOccurrences() method from NSString.
The syntax looks like this:
replacingOccurrences(of: "target", with: "replacement")
This returns a new string where all occurrences of the target substring are replaced with the replacement string.
Let's try replacing text in a string using replacingOccurrences(). Since this method comes from NSString, we need to import Foundation.
import Foundation
var s = "What's your favorite color?"
print(s.replacingOccurrences(of: "color", with: "food"))
print(s.replacingOccurrences(of: "r", with: "R"))
The output looks like this:
What's your favorite food?
What's youR favoRite coloR?
You can also use replacingOccurrences() to remove specific characters by replacing them with an empty string "".
Finding Strings
To check whether a string contains a specific substring, use the contains() method.
The syntax is like this: string.contains("substring"). It returns true if the substring is found, and false if not.
Although contains() is part of String, you still need to import Foundation to work with Character types.
Let's check whether a string contains "color" or "food".
import Foundation
var s = "What's your favorite color?"
print(s.contains("color"))
print(s.contains("food"))
The output shows true for "color" because it exists, and false for "food" because it doesn't.
true
false
That's it for replacing and finding strings in Swift.