To find the indices of all occurrences of a substring in Swift, you can use the range(of:) method in a loop to find all occurrences and store their indices in an array.
In this example,
str
with a string value.range(of:)
method to find all occurrences of a specific substring within str
and store their indices in the array.import Foundation
let str = "Hello Hello Hello"
let substr = "Hello"
var indices: [Int] = []
var searchStartIndex = str.startIndex
while let range = str.range(of: substr, range: searchStartIndex ..< str.endIndex) {
let index = str.distance(from: str.startIndex, to: range.lowerBound)
indices.append(index)
searchStartIndex = range.upperBound
}
print("Indices of all occurrences:", indices)
Indices of all occurrences: [0, 6, 12]
In this example,
str1
and str2
with different values.range(of:)
method to find all occurrences of str2
within str1
and store their indices in the array.import Foundation
let str1 = "apple banana cherry banana"
let str2 = "banana"
var indices: [Int] = []
var searchStartIndex = str1.startIndex
while let range = str1.range(of: str2, range: searchStartIndex ..< str1.endIndex) {
let index = str1.distance(from: str1.startIndex, to: range.lowerBound)
indices.append(index)
searchStartIndex = range.upperBound
}
print("Indices of all occurrences:", indices)
Indices of all occurrences: [6, 20]
In this tutorial, we learned How to find the Indices of All Occurrences of Substring in Swift language with well detailed examples.