Swift – Remove a Character in String at Specific Index

To remove a character in string at specific index in Swift, use the String method String.remove().

A simple code snippet to demonstrate how to use String.remove() method

str1.remove(at: i)

where str1 is the string and i is the index. i is of type String.Index. remove() method removes character at index i in the string str1 and returns this removed character.

Examples

In the following program, we will take a string str1, and remove the character at position i=6 using String.remove() method.

Please observe that we have to give the position as String.Index to remove() method.

main.swift

var str1 = "Hello World!"
print("Original string       : \(str1)")

var i = str1.index(str1.startIndex, offsetBy: 6)
var removed = str1.remove(at: i)
print("String after remove() : \(str1)")
print("Character Removed : \(removed)")

Output

Original string       : Hello World!
String after remove() : Hello orld!
Character Removed : W

The character W has been removed at position 6 in the string str1.

ADVERTISEMENT

Example 2 – Index Out of Bounds

If the position at which we would like remove the character, is out of bounds for the string, then Fatal error occurs with the message “String index is out of bounds”.

In the following program, we take a string of length 11. But, we try to remove the character at position 16. This causes a Fatal error.

main.swift

var str1 = "Hello World!"
print("Original string       : \(str1)")

var i = str1.index(str1.startIndex, offsetBy: 16)
var removed = str1.remove(at: i)
print("String after remove() : \(str1)")
print("Character Removed : \(removed)")

Output

Original string       : Hello World!
Fatal error: String index is out of bounds: file Swift/StringCharacterView.swift, line 60
2021-02-12 11:48:49.950818+0530 HelloWorld[1575:92958] Fatal error: String index is out of bounds: file Swift/StringCharacterView.swift, line 60

Conclusion

In this Swift Tutorial, we learned how to remove the character in string at specific position using String.remove() method, with the help of example programs.