find the kth index of a substring in a string in swift

Here's an implementation that finds the kth index of a substring in a string in Swift:

main.swift
func findKthIndex(of substring: String, at k: Int, in string: String) -> String.Index? {
    var currentIndex = string.startIndex
    var occurrence = 0

    // Iterate over each character in the string until we find the kth occurrence of the substring
    while let range = string[currentIndex..<string.endIndex].range(of: substring) {
        currentIndex = range.upperBound
        occurrence += 1

        // Return the index of the kth occurrence of the substring
        if occurrence == k {
            return range.lowerBound
        }
    }

    // Return nil if the kth occurrence of the substring is not found
    return nil
}
638 chars
19 lines

Here's an example usage of this function:

main.swift
let string = "hello world, world"
let substring = "world"
let k = 2
if let kthIndex = findKthIndex(of: substring, at: k, in: string) {
    print("Found the \(k)th index of \(substring) in \(string) at index: \(string.distance(from: string.startIndex, to: kthIndex))")
} else {
    print("Could not find the \(k)th index of \(substring) in \(string)")
}
353 chars
9 lines

This will output: "Found the 2nd index of world in hello world, world at index: 12"

gistlibby LogSnag