Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add spaces using kotlin string functions/string format

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.

like image 553
ActiveAndroidDev Avatar asked Aug 30 '26 18:08

ActiveAndroidDev


1 Answers

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 = " ")
like image 196
José Braz Avatar answered Sep 01 '26 10:09

José Braz