To find the index of a specified element in an array in Kotlin, you can use the indexOf
method of the Array class.
In this example,
arr
with integer values.indexOf
method of the array object arr
to find the index of a specific integer.indexOf
method returns the index of the first occurrence of the specified element in the array, or -1 if the element is not present.fun main(args: Array<String>) {
val arr = arrayOf(1, 2, 3, 4, 5)
val index = arr.indexOf(3)
println("Index of element 3 is: $index")
}
Index of element 3 is: 2
In this example,
arr
with string values.indexOf
method of the array object arr
to find the index of a specific string.indexOf
method returns the index of the first occurrence of the specified element in the array, or -1 if the element is not present.fun main(args: Array<String>) {
val arr = arrayOf("apple", "banana", "cherry", "date")
val index = arr.indexOf("cherry")
println("Index of element 'cherry' is: $index")
}
Index of element 'cherry' is: 2
In this tutorial, we learned How to get the Index of Specified Element in an Array in Kotlin language with well detailed examples.