To replace a substring in Swift, you can use the replacingOccurrences
method of the String class. [todo]
In this example,
str
with a string value.replacingOccurrences
method of the string object str
to replace a specific substring with another substring.replacingOccurrences
method returns a new string with the specified replacements.import Foundation
let str = "Hello World"
let newStr = str.replacingOccurrences(of: "World", with: "Swift")
print("Modified string: \(newStr)")
Modified string: Hello Swift
In this example,
str1
with a string value.replacingOccurrences
method of the string object str1
to replace a specific substring with another substring.replacingOccurrences
method returns a new string with the specified replacements.import Foundation
let str1 = "Swift is amazing"
let newStr1 = str1.replacingOccurrences(of: "amazing", with: "powerful")
print("Modified string: \(newStr1)")
Modified string: Swift is powerful
In this tutorial, we learned How to Replace a Substring in String in Swift language with well detailed examples.