To get the substring between two specific characters in Kotlin, you can use the substring
method of the String class combined with indexOf
to find the positions of the specific characters.
In this example,
str
with a value of "abcde"
.indexOf('a')
method and store it in startIndex
.indexOf('d')
method starting from startIndex
and store it in endIndex
.startIndex
and endIndex
using substring
method.fun main() {
val str = "abcde"
val startIndex = str.indexOf('a')
val endIndex = str.indexOf('d', startIndex)
val subStr = str.substring(startIndex + 1, endIndex)
println("Substring between 'a' and 'd': $subStr")
}
Substring between 'a' and 'd': bc
In this example,
str
with a value of "x123y"
.indexOf('x')
method and store it in startIndex
.indexOf('y')
method starting from startIndex
and store it in endIndex
.startIndex
and endIndex
using substring
method.fun main() {
val str = "x123y"
val startIndex = str.indexOf('x')
val endIndex = str.indexOf('y', startIndex)
val subStr = str.substring(startIndex + 1, endIndex)
println("Substring between 'x' and 'y': $subStr")
}
Substring between 'x' and 'y': 123
In this tutorial, we learned How to get Substring between two Specific Characters in Kotlin language with well detailed examples.