To replace all occurrences of a substring in a string in Swift, you can use the replacingOccurrences
method.
In this example,
str
.replacingOccurrences
method on str
with the substring to be replaced and the replacement string as arguments.replacingOccurrences
method returns a new string with all occurrences of the substring replaced.import Foundation
let str = "Hello World Hello"
let newStr = str.replacingOccurrences(of: "Hello", with: "Hi")
print(newStr)
Hi World Hi
In this example,
str
.replacingOccurrences
method on str
with the character to be replaced and the replacement character as arguments.replacingOccurrences
method returns a new string with all occurrences of the character replaced.import Foundation
let str = "Hello World Hello"
let newStr = str.replacingOccurrences(of: "o", with: "X")
print(newStr)
HellX WXrld HellX
In this tutorial, we learned How to Replace All Occurrences of a Substring in a String in Swift language with well detailed examples.