Add spaces using kotlin string functions/string format
Asked Answered
D

2

6

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.

Drucilladrucy answered 25/8, 2020 at 20:54 Comment(0)
C
14

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 = " ")
Cyanogen answered 25/8, 2020 at 21:30 Comment(3)
number.chunked(4).joinToString(separator = " ")Recto
I think your first method creates a temporary ArrayList, an IntRange, and four sub-Strings in addition to the necessary StringBuilder and result StringSkiascope
For number, which doesn't contain an exact multiple of 4 it's better to use number.reversed().chunked(4).joinToString(" ").reversed() It shows "123 4567" instead of wrong "1234 567"Nimbostratus
S
1

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

Skiascope answered 25/8, 2020 at 23:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.