Swift – Insert a Character in String at Specific Index

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

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

str1.insert(ch, at: i)

where str1 is the string, ch is the character and i is the index of type String.Index. insert() method inserts character ch at index i in the string str1.

Example

In the following program, we will take a string str1, and insert a character ch="x" at position i=5 using String.insert() method.

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

main.swift

var str1 = "Hello World!"
var ch :Character = "x"
var i = str1.index(str1.startIndex, offsetBy: 5)
str1.insert(ch, at: i)
print( str1 )

Output

Hellox World!

The character has been inserted at position 5 in the string.

ADVERTISEMENT

Example 2 – Index Out of Bounds

If the position at which we would like insert 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 insert the character at position 15. This causes a Fatal error.

main.swift

var str1 = "Hello World!"
var ch :Character = "x"
var i = str1.index(str1.startIndex, offsetBy: 15)
str1.insert(ch, at: i)
print( str1 )

Output

Fatal error: String index is out of bounds: file Swift/StringCharacterView.swift, line 60
2021-02-12 10:39:55.571491+0530 HelloWorld[1354:68290] Fatal error: String index is out of bounds: file Swift/StringCharacterView.swift, line 60

Conclusion

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