Reputation: 81
This might been asked here couple of times.. what i am trying to do adding space between every four char of a string(8888319024981442). my string length is exactly 16. String.format
is not helpful
avoiding the usage of split or creating multiple strings in memory.
is there any kotlin function/String.format that can be quickly used.
Upvotes: 6
Views: 12713
Reputation: 18577
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.)
Upvotes: 1
Reputation: 655
I don't think there is a very simple way to do this, but there is the traditional one:
val number = "8888319024981442"
val list = mutableListOf<String>()
for (i in 0..3) { list.add(number.substring(i*4, (i+1)*4))}
println(list.joinToString(" "))
EDIT
Or @IR42 simple answer
number.chunked(4).joinToString(separator = " ")
Upvotes: 14