Remove last n occurrences of a substring in a string in Swift
This tutorial will see how to remove the last n occurrences of a substring in a string in Swift. The substring is part of the parent string.
Algorithm
- Step 1: Import the foundation library. The Foundation framework is a standard library in swift that provides all the basic functionality and classes required for application building.
- Step 2: Create the function to remove the last n occurrences of a substring from the main string with a return data type of string.
The parameters of the functions are:
1. target: It is the substring that we want to delete from the parent string.
2. string: It is the parent string i.e. input string.
3. count: It is an integer that represents the number of last occurrences of the substring i.e. n. - Step 3: Divide the parent string into an array of substrings using the components method.
string.components(separatedBy: target)
: This method separates the parent string into substrings by deleting the target values in between. - Step 4: Then remove the last n(count) components from the array formed before. This will delete the last n substrings from the substring array. This task can be done using the dropLast method.
array.dropLast(count)
: This method removes the last count number of elements from an array. And returns the remaining array. - Step 5: Then join the array elements using joined method again to form the string and return it to the function.
array.joined(separator: target)
: This method join the array elements by placing the target element in between to form a string.Swift Code to remove the last n occurrences of a substring in a string
Here is the swift code to remove the last n occurrences of a substring in the string.
import Foundation func removeLastOccurrences(of target: String, in string: String, count: Int) -> String { let components = string.components(separatedBy: target) let filteredComponents = components.dropLast(count) return filteredComponents.joined(separator: target) } let input = "Hello world world world" let output = removeLastOccurrences(of: "world", in: input, count: 2) print(output)
Output:
Hello world
Also, refer to Remove leading whitespaces from a string in Swift
Leave a Reply