Swift String removeSubrange() Function



String removeSubrange() Function

The removeSubrange() method is used to remove a range of characters from the specified string. For example, we have a string "Swift programming", now we remove a range of characters or substring that is "ramm" from the given string using the removeSubrange(10, 13) method and we get:

Syntax

Following is the syntax of the removeSubrange() method −

func removeSubrange(_charRange: Range<String.Index>)

Parameters

This method takes a range of characters that we want to remove from the given string. Where the upper and lower bounds must be valid indices of the given string.

Return Value

This method returns a string after removing the elements.

Example 1

Swift program to demonstrate how to use the removeSubrange() method −

import Foundation

// Declaring a string
var str = "TutorialsPoint"
print("Original string:", str)

// Calculating index
let sIndex = str.index(str.startIndex, offsetBy: 1)
let eIndex = str.index(str.startIndex, offsetBy: 5)

// Using removeSubrange() method
str.removeSubrange(sIndex...eIndex)
print("Updated string:", str)

Output

Original string: TutorialsPoint
Updated string: TalsPoint

Example 2

Swift program to remove a substring from the given string −

import Foundation

// Declaring a string
var str = "Weather is very cold"
print("Original string:", str)

// Calculating index
let sIndex = str.index(str.startIndex, offsetBy: 10)
let eIndex = str.index(str.startIndex, offsetBy: 13)

// Specifying range
let strRange = sIndex...eIndex

// Using removeSubrange() method to remove a range of characters
str.removeSubrange(strRange)
print("Updated string:", str)

Output

Original string: Weather is very cold
Updated string: Weather isy cold
swift_strings.htm
Advertisements