To find the index of the last occurrence of a substring in Swift, you can use the range(of:options:)
method of the String class with the .backwards
option. This method allows you to search for the substring starting from the end of the string.
In this example,
str
with a value of "Hello World"
.substring
with a value of "l"
that we want to find the last occurrence of in the main string.range(of:options:)
method of the string str
to find the range of the last occurrence of the substring. We specify the .backwards
option to search from the end of the string. This method returns an optional range, so we use optional binding (if let
) to safely unwrap the result.range
constant will hold the range of the substring within the main string. We then calculate the starting index of this range by converting the range's lower bound to an integer offset from the string's start index using the distance(from:to:)
method.import Foundation
let str = "Hello World"
let substring = "l"
if let range = str.range(of: substring, options: .backwards) {
let index = str.distance(from: str.startIndex, to: range.lowerBound)
print("The starting index of the last occurrence of \"\(substring)\" is: \(index)")
} else {
print("Substring \"\(substring)\" not found")
}
The starting index of the last occurrence of "l" is: 9
In this example,
str
with a value of "Programming Programming"
.substring
with a value of "mm"
that we want to find the last occurrence of in the main string.range(of:options:)
method of the string str
to find the range of the last occurrence of the substring. We specify the .backwards
option to search from the end of the string. This method returns an optional range, so we use optional binding (if let
) to safely unwrap the result.range
constant will hold the range of the substring within the main string. We then calculate the starting index of this range by converting the range's lower bound to an integer offset from the string's start index using the distance(from:to:)
method.import Foundation
let str = "Programming Programming"
let substring = "mm"
if let range = str.range(of: substring, options: .backwards) {
let index = str.distance(from: str.startIndex, to: range.lowerBound)
print("The starting index of the last occurrence of \"\(substring)\" is: \(index)")
} else {
print("Substring \"\(substring)\" not found")
}
The starting index of the last occurrence of "mm" is: 18
In this tutorial, we learned How to find the Index of Last Occurrence of Substring in Swift language with well detailed examples.