Replace A Word In A String In Swift
Code snippet for how to Replace A Word In A String In Swift with sample and detail explanation
With Swift, you can easily replace a word in a string in just a few steps. This article is designed to walk you through the process of how you can accomplish this task.
Code snippet for Replacing a Word in a String in Swift
let originalString = "Hello, World!"
let replacedString = originalString.replacingOccurrences(of: "World", with: "Swift")
print(replacedString) // prints "Hello, Swift!"
Code Explanation for Replacing a Word in a String in Swift
The Swift language makes replacing a word in a string quite straightforward with the replacingOccurrences(of:with:)
method.
Let’s break down the sample code provided.
let originalString = "Hello, World!"
Here, we define a constant originalString
which holds the value “Hello, World!“.
let replacedString = originalString.replacingOccurrences(of: "World", with: "Swift")
On this line, we make use of the replacingOccurrences(of:with:)
method provided by the Swift standard library. What this function does is that it searches through the originalString
for occurrences of the first parameter (“World”), removes them, and replaces them with the second parameter (“Swift”). The method returns a new string with the substitutions made, which we store in a new constant, replacedString
.
print(replacedString) // prints "Hello, Swift!"
Finally, we use the print
function to print our new replacedString
to the console. The output will now be “Hello, Swift!” because the instances of the word “World” in the originalString
have been replaced with “Swift”.
So, as you can see, the replacingOccurrences(of:with:)
method is quite straightforward to use. It can be highly useful in various situations, such as text manipulation and data cleaning. With this piece of knowledge, you have an additional tool in your Swift programming toolkit.