OneBite.Dev - Coding blog in a bite size

Remove A Character From A String In Swift

Code snippet for how to Remove A Character From A String In Swift with sample and detail explanation

Manipulating strings is a common task in developing any software. This article is a simple guide that will explain how to remove a character from a string in Swift.

Code snippet: Remove A Character from a String in Swift

To remove a specific character from a string in Swift, you can utilize the replacingOccurrences(of:with:) method that is built into the String structure. Here is a basic example:

var str = "Hello, World!"
str = str.replacingOccurrences(of: "l", with: "")

After executing these lines of code, the string str should now hold the value of “Heo, Word!” - where all instances of the letter “l” have been removed.

Code Explanation: Remove A Character from a String in Swift

Let’s go through the code snippet and understand it step by step.

First, we declare a variable str of type String and assign it a string value “Hello, World!“.

var str = "Hello, World!"

In the second line of code, we call the replacingOccurrences(of:with:) method on the str variable. This method is embedded within Swift’s String structure and is used to replace all occurrences of a specified substring within the string with another substring.

str = str.replacingOccurrences(of: "l", with: "")

We specify the of parameter with the character “l” that we intend to remove from the string. In the with parameter, we pass an empty string "", which instructs Swift to replace all occurrences of “l” with nothing - effectively removing it.

Thus, after this line of execution, all instances of the letter “l” are removed from our original string and the variable str now holds the new string value “Heo, Word!“.

In this simple, yet effective way, you can remove any character from a string in Swift using the replacingOccurrences(of:with:) method.

swift