OneBite.Dev - Coding blog in a bite size

Replace A Substring Within A String In Swift

Code snippet for how to Replace A Substring Within A String In Swift with sample and detail explanation

Swift is a flexible and competent programming language that offers numerous functionalities, one of which is the ability to replace a substring within a string. In this simple article, we will learn how to replace a substring within a string in Swift with the help of a code snippet and a detailed explanation of the code.

Code Snippet For Replacing A Substring Within A String In Swift

Below is a small snippet in Swift that exemplifies how to replace a substring within a given string:

let originalString = "Hello, Globe!"
let replacedString = originalString.replacingOccurrences(of: "Globe", with: "World")
print(replaceString) // prints "Hello, World!"

Code Explanation For Replacing A Substring Within A String In Swift

Let’s go through the code step by step.

  1. We begin, by initializing the original string:
let originalString = "Hello, Globe!"

This line of code simply initializes a string variable originalString with the value “Hello, Globe!“.

  1. The following line of code uses the replacingOccurrences(of:with:) function in Swift to replace a substring within a string:
let replacedString = originalString.replacingOccurrences(of: "Globe", with: "World")

The replacingOccurrences(of:with:) function is called on the originalString. It takes two arguments: - the first argument, of, is a string that signifies the substring you want to replace. - the second argument, with, is a string that you want to replace the first argument with. In our code, we are replacing “Globe” with “World”.

  1. Lastly, we print the modified string:
print(replaceString)

This line of code prints out the replaced string. So the output will be “Hello, World!“.

Just as a side note, the replacingOccurrences(of:with:) function does not modify the original string. Instead, it creates a new string with the replaced substrings. If the substring to replace does not exist in the original string, it simply returns the original string.

Through this simple Swift code snippet and its step by-step-explanation, we hope you have understood how to replace a substring within a string in Swift. Experiment with different substrings and replacement strings for better understanding.

swift