String insert() in Swift

In this tutorial, we will discuss about insert() in Swift with its Syntax, implementation, and examples.

String insert() is nothing but as the name suggests inserting a string at the specific position in a given string.

We will cover these things:

  • Syntax of insert().
  • insert() function to add at the start of a string.
  • insert() function to add at the end of a string.
  • insert() function to add at any specific position of a string.

Syntax of String insert()

The syntax of String insert in Swift is as follows-

string.insert(char: character, at: string.index)

string is the actual string where all the modifications need to be done

character is the character to be inserted

index is the position where we need to insert the character

For example, we need to insert a character at any specific position.

Add a string at the start of the string

Here’s an example to insert a string at the start of the string-

CodeSpeedy

We want it as-

-CodeSpeedy

We need to add – at the start of the string. We will use insert function with the parameter as the startindex.

Here’s the implementation-

var str = "CodeSpeedy"
str.insert("-", at: str.startIndex)
print(str)

-CodeSpeedy

Add a string at the end of the string

Here’s an example-

CodeSpeed

We need it as CodeSpeedy.

We need to add y at the end of CodeSpeed. We will use the insert() function and add y at the end of the string.

Here’s the implementation-

var str = "CodeSpeed"
str.insert("y", at: str.endIndex)
print(str)
CodeSpeedy

So we have completed the task to add y at the end of the string.

Add a string at a specific position of the given string

So we have already printed the string where we have inserted the string at the start and end of the given string. Now we will proceed to insert the string at any specific position. Here we will use the parameter offset as-

Here’s an example-

Input-CodeSpeedy

Output-Code-Speedy

We will add “-” at the specific position i.e. after e.

Implementation-

var str = "CodeSpeedy"
str.insert("-", at: str.index(str.startIndex, offsetBy:4))
print(str)

Code-Speedy

So we have completed the task to insert or add a string at the start, end and at the specific position of any string.

Leave a Reply

Your email address will not be published. Required fields are marked *