Swift String remove()

The remove() method removes a character in the string at the specified position.

Example

var greet = "Good-morning"

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

// remove the character greet.remove(at: i)
print(greet) // Output: Goodmorning

remove() Syntax

The syntax of the string remove() method is:

string.remove(at: i)

Here, string is an object of the String class.


remove() Parameters

The remove() method takes only one parameter.

  • i - index of the character to remove

remove() Return Values

  • returns a character that was removed from string

Example: Swift string remove()

var message = "Hello, World!"

print("Before Removing:", message)

// position of the character to remove
var i = message.index(message.startIndex, offsetBy: 12)

// remove the character at index i var removed = message.remove(at: i)
print("After Removing:", message) print("Removed Character:", removed)

Output

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

Here, we have removed "!" from the message string. The removed character is stored in the removed variable.

Did you find this article helpful?