I am trying to split string with chunks of 16 chars length. So first of all I create string with 64 length
val data = "Some string"
data = String.format("%-64s", data)
Then I split it with regex
val nameArray = data.split(Regex("(?<=\\G.{16})").toPattern())
Here I expext to get 4 chunks with 16 chars, but I got only 2, where first is 16 and second is 48.
Where am I wrong here?
Kotlin 1.2.61, Oracle JDK 1.8.0_181-b13, Windows 10
data.chunked(16)
should be sufficient to solve the problem as you described it. It should be available in the version you use, since its documented as such here.
I have tried your approach and the one from Keng, but with very different results as described here.
https://pl.kotl.in/HJpQSfdqi
import java.net.URI
import java.util.*
import java.time.LocalDateTime
import java.time.temporal.*
/**
* You can edit, run, and share this code.
* play.kotlinlang.org
*/
fun main() {
var data = "Some string"
data = String.format("%-64s", data)
println(data.length)
// 1st approach
var nameArray = data.split(Regex("(?<=\\G.{16})").toPattern())
println(nameArray)
nameArray.forEach{ it -> println(it.length) }
println()
// 2nd approach
nameArray = data.split(Regex(".{16}").toPattern())
println(nameArray)
nameArray.forEach{ it -> println(it.length) }
println()
data.chunked(16).forEach{ it -> println(it.length) }
}
When I run that code, the proposed regex-methods return arrays of length 5, which is caused by an empty element at the end. I don't quite understand why, but I hope this helps to solve your problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With