I don't think there's an answer which is both simple and elegant and avoids all temporary objects.
For the former, IR42's use of chunked()
is probably best.
Here's a stab at the latter:
val number = "8888319024981442"
val result = buildString {
for (i in 0 until number.length) {
if (i % 4 == 0 && i > 0)
append(' ')
append(number[i])
}
}
println(result) // '8888 3190 2498 1442'
This creates only a single StringBuilder
, and then a single String
from it — which is the minimum possible*. It's a bit ugly and long-winded, but if avoiding all temporary objects is really important**, then that's probably about the best you can do.
(* Or at least, the minimum possible given the conditions. For better performance, consider passing the StringBuilder
itself on without creating a String
from it. Even better, use an existing StringBuilder
in instead of creating one at all. But of course all that needs changes to the surrounding code.)
(** While there are situations in which this is really important, in practice they're pretty unusual. I'd recommend going with the simple version until you've done some profiling and proved that this is a bottleneck and that the complex version really does perform better in your case. And even then, fold it into a utility function to keep the main code clear.)
number.chunked(4).joinToString(separator = " ")
– Recto