2

Is there a quick way to split a String by fixed number of chars in Kotlin?

I need to split this 544A1609B62E, lowercase it, add : where needed and achieve this: 54:4a:16:09:b6:2e.

What would be the idiomatic way to do it?

lidkxx
  • 2,731
  • 2
  • 25
  • 44

2 Answers2

9

In Kotlin 1.2 you can do this:

"544A1609B62E".toLowerCase().chunked(2).joinToString(":")

The chunked function is new in Kotlin 1.2. It splits a collection into chunks of the given size.

Doing this in Kotlin 1.1 or lower is a bit more cumbersome. You could look at the answers in the question posted by @NSimon here: Java: How to split a string by a number of characters?

marstran
  • 26,413
  • 5
  • 61
  • 67
  • Thanks, this is exactly what I am looking for... in the future :) I ended up doing something like this: private fun formatMacAddress(): String { return id.toLowerCase() .mapIndexed { index, char -> if (index != 0 && index % 2 == 0) ":$char" else "$char" } .joinToString("") } probably won't format in the comment, but you get the idea... – lidkxx Nov 07 '17 at 10:38
  • @lidkxx Nice, that looks actually pretty good! Btw, you can format code in comments by wrapping it in backticks ( ` ) – marstran Nov 07 '17 at 11:30
1

Another try in Kotlin,

val sampleString = "544A1609B62E"
        var i = 0
        var sampleBuffer = "";
        while(i < sampleString.length - 2) {
            sampleBuffer = sampleBuffer.plus(sampleString.toLowerCase ().substring(i, i + 2)).plus(":")
            i += 2
        }

        sampleBuffer = sampleBuffer.plus(sampleString.toLowerCase().substring(i))
        Log.e(TAG, sampleBuffer)
Febi M Felix
  • 2,799
  • 1
  • 10
  • 13