Create an array with the new strings. Find the range of first matching substring “black” in the string using range(of:)
. And replace with the new string in the range using replaceSubrange(_:with:)
method.
Then continue the loop till last element of the array.
var mString = "my car is black, my phone is black"
["blue","red"].forEach {
if let range = mString.range(of: "black") {
mString.replaceSubrange(range, with: $0)
}
}
print(mString)
my car is blue, my phone is red
Check Swift String Cheat Sheet
0
solved Replace occurrences in String