Open In App

How to Insert a Character in String at Specific Index in Swift?

Last Updated : 05 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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




// Swift program to insert a new
// character value into the string
import Swift
  
// Creating an string
var string = "GF"
  
// Calling the insert() functions to 
// insert a character G to the above string
string.insert("G", at: string.endIndex)
  
// Getting the inserted string
print(string)


Output:

GFG

Example 2:

Swift




// Swift program to insert a new
// character value into the string
import Swift
  
// Creating an string
var string = "F"
  
// Calling the insert() functions to 
// insert a character G to the above string
string.insert("G", at: string.startIndex)
string.insert("G", at: string.endIndex)
  
// Getting the inserted string
print(string)


Output:

GFG

Example 3:

Swift




// Swift program to insert a new
// character value into the string
import Swift
  
// Creating an string
var string = "Geeksfor"
  
// Calling the insert() functions to 
// insert a string "Geeks" to the above string
string.insert(contentsOf: "Geeks", at: string.endIndex)
  
// Getting the inserted string
print(string)


Output:

GeeksforGeeks


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads