To remove a specific substring from a string in Swift, you can use the `replacingOccurrences` method of the String class.
In this example,
str
with a value of "Hello World"
.replacingOccurrences
method of the string object str
to replace the substring "World"
with an empty string ""
.replacingOccurrences
method returns a new string with the specified replacements.str
to the console.import Foundation
var str = "Hello World"
str = str.replacingOccurrences(of: "World", with: "")
print("Modified string:", str)
Modified string: Hello
In this example,
text
with a value of "I like apple pie"
.replacingOccurrences
method of the string object text
to replace the substring "apple"
with an empty string ""
.replacingOccurrences
method creates and returns a new string with the specified replacements.text
to the console.import Foundation
var text = "I like apple pie"
text = text.replacingOccurrences(of: "apple", with: "")
print("Modified string:", text)
Modified string: I like pie
In this tutorial, we learned How to Remove specific Substring in Swift language with well detailed examples.