Swift Program to Insert a string into another string


Swift provides a function named insert() to insert a string into another string. The insert(at:) function adds a new character or string in the current string at the specified position.

Input

String = “Program to learn”
New String = “Swift”

Output

String = Swift Program to learn”

Here we insert a new string in the input String at index 1. So we get “Swift Program to learn” in the output.

Syntax

func insert(newVal, at: idx)

Where newVal represents a new string which we want to insert into the given string, and idx is the valid index to where we insert the newVal in the existing string.

Algorithm

  • Step 1 − Create a string.

  • Step 2 − Create another string which we will insert into the given string.

  • Step 3 − Find the index value using the index() function at which we will insert the new string.

  • Step 4 − Now insert the new string into the given string using the insert() function.

  • Step 5 − Print the output.

Example

In the following Swift program, we will insert a string into another string. To do this task we will create two original strings and the new string. The original string is the main string in which we will insert the new string. Then we calculate the index value at which we will insert the new string using index() and then using the insert() function we will insert the new string in the original string at the specified index.

import Foundation
import Glibc

var originalStr = "my blue car"
let newStr = "color "

print("Original String:", originalStr)

// Finding index
let idx = originalStr.index(originalStr.startIndex, offsetBy: 3)

// Inserting new string in the current string
originalStr.insert(contentsOf: newStr, at: idx)

print("Updated String:", originalStr)

Output

Original String: my blue car
Updated String: my color blue car

Conclusion

So this is how we insert a string into another string. Using the insert() function you can insert any string or character at any index in the specified string. But remember the index should be a valid index. If you insert any invalid syntax, then this method will throw an exception.

Updated on: 09-May-2023

407 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements