Kotlin – Find index of Nth occurrence of Substring

Find index of Nth occurrence of a substring in a string in Kotlin

To find the index of nth occurrence of a substring (search string) in a string in Kotlin, you can use a While loop to iterate from the starting of the string, keep a count of the occurrences of substring, and break the loop when you get the index of Nth occurrence.

Consider a scenario, where we are given a content string, and we need to find the second occurrence of the search string "apple" in the content string.

"apple, banana, apple, apple, fig"
                |
                ^  <- 2nd occurrence
                15 <- index

The following function findNthOccurrence() takes two parameters. The first parameter is the content string, and the second parameter is the search string or substring.

fun findNthOccurrence(string: String, substring: String, n: Int): Int {
    var count = 0
    var index = -1
    var currentIndex = 0

    while (count < n) {
        index = string.indexOf(substring, currentIndex)
        if (index == -1) {
            break
        }
        count++
        currentIndex = index + 1
    }

    return index
}

The function returns an integer specifying the index of the Nth occurrence of the search string in the given string.

If there is no occurrence of the search string, then the function returns -1.

Examples

Find index of 2nd occurrence of “apple” in the string

In the following program, we take a string value in str variable. We would like to find the index of the second occurrence of the search string "apple".

Kotlin Program

fun findNthOccurrence(string: String, substring: String, n: Int): Int {
    var count = 0
    var index = -1
    var currentIndex = 0

    while (count < n) {
        index = string.indexOf(substring, currentIndex)
        if (index == -1) {
            break
        }
        count++
        currentIndex = index + 1
    }

    return index
}

fun main() {
    val originalString = "apple, banana, apple, apple, fig"
    val substring = "apple"
    val occurrenceNumber = 2

    val nthIndex = findNthOccurrence(originalString, substring, occurrenceNumber)
    println("Index of occurrence-$occurrenceNumber : $nthIndex")
}

Output

Index of occurrence-2 : 15

Explanation

"apple, banana, apple, apple, fig"
                |
                ^  <- 2nd occurrence
                15 <- index