To get all possible substrings of a string in Kotlin, you can use nested loops to iterate through each combination of start and end indices.
In this example,
str
with a value of "Hello"
.substrings
to store all substrings.substring
method and add it to the substrings
list.substrings
list.fun main(args: Array<String>) {
val str = "Hello"
val substrings = mutableListOf<String>()
for (i in str.indices) {
for (j in i + 1..str.length) {
substrings.add(str.substring(i, j))
}
}
println("All substrings: $substrings")
}
All substrings: [H, He, Hel, Hell, Hello, e, el, ell, ello, l, ll, llo, l, lo, o]
In this tutorial, we learned How to get all the possible Substrings of a String in Kotlin language with well detailed examples.