I need to split a string into a few parts that contain N letters each. For example
str = "Hello World! Kotlin is amazing!"
split_into_n(str, 3) = ["Hel", "lo ", "Wor", "ld!", " Ko", "tli", "n i", "s a", "maz", "ing", "!"]
I have tried regex, but it does not seem to work. I have tried using split methods but it doesn't work either. Any help would be appreciated :)
CodePudding user response:
chunked()
extension function does exactly this:
val str = "Hello World! Kotlin is amazing!"
println(str.chunked(3))
// [Hel, lo , Wor, ld!, Ko, tli, n i, s a, maz, ing, !]
CodePudding user response:
The length of the resulting array will be the length of the original array divided by N but if there is a remainder, you need an additional element.
val result=Array<String>(str.length/n (str.length%n).sign())
str.length/n
is the resulting length without the last element if the original lebgth is not dividable by n
.
str.length%n
results in 0
if the length is dividable by n
and a positive number (remainder) if it is not.
sign
returns 1
if the value is positive and 0
if the value is 0
.
After that, you can just fill the array with substrings:
for(i in 0..result.length){
result[i]=str.substring(i*n,min((i 1)*n,str.length))
}
This loops over all indexes of the resulting array and sets the corresponding elements to substrings of str
.
The start index is the index of the resulting array multiplied by 3 and the end index is the index before the next element (or the last total length).
Combined, it would look like this:
import kotlin.math
fun splitIntoN(str,n){
val result=Array<String>(str.length/n (str.length%n).sign())
for(i in 0..result.length){
result[i]=str.substring(i*n,min((i 1)*n,str.length))
}
}