Kotlin – Find index of last occurrence of substring in a string

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

To find the index of last occurrence of a substring (search string) in a string in Kotlin, you can use String.lastIndexOf() function.

Call lastIndexOf() function on the given string object str, and pass the search string as argument.

str.lastIndexOf(searchStr)

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

"apple is red. cherry is red."  <- string
                         |      <- "red" is search string
                         ^  <- last occurrence of search string
                         24 <- index

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

We can also search the string by ignoring the case. For that, we have to pass a value of true for the ignoreCase parameter.

str.lastIndexOf(searchStr, ignoreCase=true)

We can also specify a specific start for searching the search string searchStr in given string str. For that, we have to pass an integer value of start index for the parameter startIndex.

str.lastIndexOf(searchStr, startIndex=5)

Please note that the search happens from specified startIndex towards the starting of the string.

Examples

Find index of last occurrence of “red” in the string

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

Kotlin Program

fun main() {
    val str = "apple is red. cherry is red."
    val searchStr = "red"
    val index = str.lastIndexOf(searchStr)
    println("Last index : $index")
}

Output

Last index : 25

Explanation

apple is red. cherry is red.
                        |
                        ^  <- last occurrence of search string
                        24 <- index

Find index of last occurrence of “red” in the string, ignoring the case

In this example, we will search for the last occurrence of the string "red" in the given string str, by ignoring the case.

Kotlin Program

fun main() {
    val str = "Apple is RED. Cherry is RED."
    val searchStr = "red"
    val index = str.lastIndexOf(searchStr, ignoreCase = true)
    println("Last index : $index")
}

Output

Last index : 24

Find index of last occurrence of “red” in the string, with a specific start index for search

In this example, we will search for the string "red" in the given string str, after a specific start index.

Kotlin Program

fun main() {
    val str = "apple is red. cherry is red."
    val searchStr = "red"
    val index = str.lastIndexOf(searchStr, startIndex = 15)
    println("Last index : $index")
}

Output

Last index : 9

Explanation

apple is red. cherry is red.
                |   <- start index = 15, search from here towards index = 0
         red
         ^
         |
         9  <- index of "red" in string