Get the index of search element in the Array in Kotlin
To get the index of given search element in the Array in Kotlin, you can use Array.indexOf()
function.
["apple", "banana", "cherry", "mango"]
0 1 2 3
"cherry" <- search element
2 <- is the index
Call the function indexOf()
on the Array object and pass the given search element as argument.
arr.indexOf(searchElement)
The function returns the index of the first occurrence of search element in the Array, if the search element is present. If in case the search element is not present, then the function returns -1
.
Examples
Get the index of “cherry” in the Array
In the following program, we take an Array of strings in arr
and a search element in searchElement
. We find the index of the search element in the array using Array.indexOf()
function.
Kotlin Program
fun main(args: Array<String>) {
val arr = arrayOf<String>("apple", "banana", "cherry", "mango")
val searchElement = "cherry"
val index = arr.indexOf(searchElement)
println("index : $index")
}
Output
index : 2
Explanation
["apple", "banana", "cherry", "mango"]
0 1 2 3
"cherry" <- search element
2 is the index
What is the index of search element if the search element is not present in the Array
In the following program, we take an Array of strings in arr
and a search element in searchElement
. The value in searchElement
is such that it is not present in the given Array arr
.
Kotlin Program
fun main(args: Array<String>) {
val arr = arrayOf<String>("apple", "banana", "cherry", "mango")
val searchElement = "fig"
val index = arr.indexOf(searchElement)
println("index : $index")
}
Output
index : -1
Since the search element is not present in the Array, indexOf()
function returned -1
.