To get all possible K length substrings in a string in Kotlin, you can use a loop to iterate through the string and extract substrings of length K.
In this example,
str
with a value.k
that specifies the length of the substrings we want to extract.substrings
to store the substrings.for
loop to iterate through the string, stopping at a position where a substring of length k
can still be extracted.substring
method of the string object str
to extract a substring of length k
starting at the current index i
.substrings
list.substrings
list.fun main(args: Array<String>) {
val str = "abcdefg"
val k = 3
val substrings = mutableListOf<String>()
for (i in 0..str.length - k) {
substrings.add(str.substring(i, i + k))
}
for (substring in substrings) {
println(substring)
}
}
abc bcd cde def efg
In this example,
str
with a different value.k
that specifies the length of the substrings we want to extract.substrings
to store the substrings.for
loop to iterate through the string, stopping at a position where a substring of length k
can still be extracted.substring
method of the string object str
to extract a substring of length k
starting at the current index i
.substrings
list.substrings
list.fun main(args: Array<String>) {
val str = "hello world"
val k = 4
val substrings = mutableListOf<String>()
for (i in 0..str.length - k) {
substrings.add(str.substring(i, i + k))
}
for (substring in substrings) {
println(substring)
}
}
hell ello llo lo w o wo wor worl orld
In this tutorial, we learned How to get all the possible K length Substrings in a String in Kotlin language with well detailed examples.