Reputation: 1748
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
Upvotes: 5
Views: 1028
Reputation: 2557
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.
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.
Upvotes: 1
Reputation: 53101
Here's how I split it with regex
.{16}
Note: I'm not sure what all the other stuff in there is trying to do, maybe string specific items?
Upvotes: 0