To find the index of the last occurrence of a substring in Kotlin, you can use the lastIndexOf
method of the String class.
In this example,
str
with a string value.lastIndexOf
method of str
to find the index of the last occurrence of a specific substring within str
.lastIndexOf
method returns the index of the last occurrence of the substring in the string.fun main() {
val str = "Hello World, Hello Kotlin"
val lastIndex = str.lastIndexOf("Hello")
println("Last index of substring is: $lastIndex")
}
Last index of substring is: 13
In this example,
str1
and str2
with different values.lastIndexOf
method of str1
to find the index of the last occurrence of str2
within str1
.lastIndexOf
method returns the index of the last occurrence of str2
in str1
.fun main() {
val str1 = "apple banana cherry banana"
val str2 = "banana"
val lastIndex = str1.lastIndexOf(str2)
println("Last index of substring is: $lastIndex")
}
Last index of substring is: 20
In this tutorial, we learned How to find the Index of Last Occurrence of Substring in Kotlin language with well detailed examples.