How to remove a specific character from a string in Swift? (original) (raw)

Last Updated : 5 Jul, 2022

Swift language supports different types of generic collections and a string is one of them. A string is a collection of alphabets. In the Swift string, we check the removal of a character from the string. To do this task we use the remove() function. This function is used to remove a character from the string. It will return a character that was removed from the given string.

Syntax:

string.remove(at: i)

Here string is an object of the string class.

Parameters: This function accepts a parameter that is illustrated below:

Return Value: This function returns a character that was removed from the specified string.

Example 1:

Swift `

// Swift program to removes a character from the string import Swift

// Creating an string var string = "GFG"

// Position of the character to remove var i = string.index(string.startIndex, offsetBy: 1)

// Removing the character var removed_String = string.remove(at: i)

// Getting the string after removal of character print(string)

// Getting the removed character print(removed_String)

`

Output:

GG F

Example 2:

Swift `

// Swift program to removes a character from the string import Swift

// Creating an string var string = "Geeks"

print("Before Removing:", string)

// Position of the character to remove var i = string.index(string.startIndex, offsetBy: 4)

// Removing the character var removed_String = string.remove(at: i)

print("After Removing:", string)

print("Removed Character:", removed_String)

`

Output:

Before Removing: Geeks After Removing: Geek Removed Character: s