5

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

enter image description here

2

2 Answers 2

1
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.

Sign up to request clarification or add additional context in comments.

Comments

0

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.