OneBite.Dev - Coding blog in a bite size

Find The Position Of The Last Occurrence Of A Substring In A String In Swift

Code snippet for how to Find The Position Of The Last Occurrence Of A Substring In A String In Swift with sample and detail explanation

In Swift, finding the position of the last occurrence of a substring in a string can be a common task, especially while parsing strings or during several algorithm-related tasks. This article details a simple approach to solve this problem with Swift.

Code snippet for Finding the Position Of The Last Occurrence Of A Substring In A String in Swift

Here is a Swift function for finding the last occurrence of a substring in a string:

let str = "Hello, Swift! Swift is a powerful language."
if let range = str.range(of: "Swift", options: .backwards) {
    let lastIndex = distance(from: str.startIndex, to: range.lowerBound)
    print("The last index of Swift is \(lastIndex).")
} else {
    print("Swift not found")
}

Code Explanation for Finding the Position Of The Last Occurrence Of A Substring In A String in Swift

In the above code, we have a string str that reads “Hello, Swift! Swift is a powerful language.”. We want to find the index of the last occurrence of the substring “Swift” in this string.

We use the range(of: options:) method from Swift’s String class, passing the substring and the backwards option. This method return an optional Range indicating the start and end indices of the last occurrence of the substring. If the substring is not found, it returns nil.

The if let statement facilitates optional binding, to provide a new constant range only if the call to str.range(of: "Swift", options: .backwards) returns a non-nil value.

Then, the distance(from: str.startIndex, to: range.lowerBound) line calculates the position of the substring from the beginning of the main string, which is our result. If the substring was found, we print its last index; if not, we print “Swift not found”.

Remember that string indices in Swift aren’t integers, which is why we use the distance(from:to:) method to calculate the position.

This approach can be applied to find the last occurrence of any substring in a string. Just replace "Swift" with your desired substring.

swift