Remove a specific character from a string in Swift

In this tutorial, we will learn how to remove a specific character from a string in Swift with a simple example.

How to remove a specific character from a string in Swift

To remove the specific character from a string we are using remove() method to remove a character in the string at the specified potion. The syntax of the string remove method is:

string.remove(at: i)

The string “Hello, World!” is assigned to a variable named “message”. The function “print” is used to display the original message. The variable “i” is assigned to the index of the character to remove using the “index” function. The “index” function takes two arguments starting index and an offset. The starting index is the beginning of the string (message.startindex), and the offset is 12.  So, the variable “i” will represent the index of the character “!”.

The “remove” function is used to remove the character at index “i” from the string “message”. The removed character is stored in the “removed” variable.

Finally, the “print” function is used again to display the update “message” string without the remove character, as well as the removed character itself.

var message = "Hello, World!"
print("Before removing:", message)

//Position of the character want to remove
var i = message.index(message.startindex, offsetBy: 12)

//Remove the character at index i
var removed = message.remove(at: i)

//To see the new string after removing the specific character
print("After Removing:", message)

//To see the removed character from the string 
print("Removed Character:", removed)

The output of the code will be:

Before Removing: Hello, World!
After Removing: Hello, World
Removed Character: !

Leave a Reply

Your email address will not be published. Required fields are marked *