Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Swift String remove() Function



String remove() Function

The remove() method of the String structure is used to remove specified characters from the given position. For example, we have a string "My Car", now we use the remove(at: 1) method to remove the character present at index 1. So the final answer is

Syntax

Following is the syntax of the remove() method −

func remove(at x: String.Index)-> Character

Parameters

This function takes only one parameter which is x. Here x represents the position of the character that we want to remove. The value of x must be a valid index of the string.

Return Value

This method returns the removed character.

Example 1

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

import Foundation

// Declaring a string
var str = "Swift"

print("Original String:", str)

// Removing character from the string
// Using remove(at:) function
if let res = str.firstIndex(of: "w"){
   str.remove(at: res)
}

print("Modified String:", str)

Output

Original String: Swift
Modified String: Sift

Example 2

Swift program to remove a character from the given string −

var str = "Welcome Swift"
print("Original string: \(str)")

// Define the index of the character "c" to remove
let index = str.index(str.startIndex, offsetBy: 3)

// Check if the index is within the given bounds
if index < str.endIndex {

Using the remove(at) function to remove the character at the specified index
str.remove(at: index)
   print("Updated String: \(str)")
} else {
   print("Invalid index.")
}

Output

Original string: Welcome Swift
Updated String: Welome Swift
swift_strings.htm
Advertisements