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?
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?
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?
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)