Kotlin – Find index of substring in a string

Find index of substring in a string in Kotlin

To find the index of a substring in a string in Kotlin, you can use String.indexOf() function.

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

str.indexOf(searchStr)

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

"apple is red. cherry is red."  <- string
          |                     <- "red" is search string
          ^ <- first occurrence of search string
          9 <- 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 true for the ignoreCase parameter.

str.indexOf(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.indexOf(searchStr, startIndex=5)

Examples

Find index 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 first occurrence of the search string "red".

Kotlin Program

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

Output

Index : 9

Explanation

apple is red. cherry is red.
         |
         ^  <- first occurrence of search string
         9  <- index

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

In this example, we will search for 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.indexOf(searchStr, ignoreCase = true)
    println("Index : $index")
}

Output

Index : 9

Find index 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.indexOf(searchStr, startIndex = 15)
    println("Index : $index")
}

Output

Index : 24

Explanation

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