To find the indices of all occurrences of a substring in Kotlin, you can use the findAll
method of the Regex class combined with the map
function to extract the indices.
In this example,
str
with a string value.findAll
method of the Regex class to find all occurrences of a specific substring within str
.map
function to extract the indices of these occurrences.fun main() {
val str = "Hello Hello Hello"
val regex = Regex("Hello")
val indices = regex.findAll(str).map { it.range.first }
println("Indices of all occurrences: ${indices.toList()}")
}
Indices of all occurrences: [0, 6, 12]
In this example,
str1
and str2
with different values.findAll
method of the Regex class to find all occurrences of str2
within str1
.map
function to extract the indices of these occurrences.fun main() {
val str1 = "apple banana cherry banana"
val str2 = "banana"
val regex = Regex(str2)
val indices = regex.findAll(str1).map { it.range.first }
println("Indices of all occurrences: ${indices.toList()}")
}
Indices of all occurrences: [6, 20]
In this tutorial, we learned How to find the Indices of All Occurrences of Substring in Kotlin language with well detailed examples.