Search code examples
stringkotlinreplaceallstring.format

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.


Solution

  • 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 = " ")