How to Insert a Character in String at Specific Index in Swift?
Last Updated :
05 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 will insert a new character value into the string. To do this task we use the insert() function. This function is used to insert a new character value into the string. It will return a string by inserting a given char into the string.
Syntax:
string.insert(char: Character, at: string.index)
Here string is an object of the String class.
Parameters: This function accepts two parameters that are illustrated below:
- char: This is a character that will be inserted.
- at: This is the index where the character will be inserted.
Return Value: This function returns a string by inserting a given character into the string.
Example 1:
Swift
import Swift
var string = "GF"
string.insert( "G" , at: string.endIndex)
print (string)
|
Output:
GFG
Example 2:
Swift
import Swift
var string = "F"
string.insert( "G" , at: string.startIndex)
string.insert( "G" , at: string.endIndex)
print (string)
|
Output:
GFG
Example 3:
Swift
import Swift
var string = "Geeksfor"
string.insert(contentsOf: "Geeks" , at: string.endIndex)
print (string)
|
Output:
GeeksforGeeks
Share your thoughts in the comments
Please Login to comment...