To find the index of a substring in Swift, you can use the range(of:)
method of the String class. This method returns the range of the first occurrence of the specified substring, which you can then use to determine the starting index.
In this example,
str
with a value of "Hello World"
.substring
with a value of "World"
that we want to find in the main string.range(of:)
method of the string str
to find the range of the first occurrence of the substring. 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 = "World"
if let range = str.range(of: substring) {
let index = str.distance(from: str.startIndex, to: range.lowerBound)
print("The starting index of \"(substring)\" is: (index)")
} else {
print("Substring \"(substring)\" not found")
}
The starting index of "World" is: 6
In this example,
str
with a value of "Swift Programming"
.substring
with a value of "Prog"
that we want to find in the main string.range(of:)
method of the string str
to find the range of the first occurrence of the substring. 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 = "Swift Programming"
let substring = "Prog"
if let range = str.range(of: substring) {
let index = str.distance(from: str.startIndex, to: range.lowerBound)
print("The starting index of \"(substring)\" is: (index)")
} else {
print("Substring \"(substring)\" not found")
}
The starting index of "Prog" is: 6
In this tutorial, we learned How to find the Index of Substring in Swift language with well detailed examples.