Search

Dark theme | Light theme

December 10, 2022

Kotlin Kandy: Padding Strings

Kotlin extends the String class with a couple of padding methods. These methods allows us to define a fixed width a string value must occupy. If the string itself is less than the fixed width then the space is padded with spaces or any other character we define. We can pad to the left or the right of the string using the padStart and padEnd methods. When we don’t define an argument a space character is used for padding, but we can also add our own custom character as argument that will be used as padding character.

In the following example code we use the padEnd and padStart methods with and without arguments:

assert("Kotlin".padEnd(12) == "Kotlin      ")
assert("Kotlin".padStart(12) == "      Kotlin")

assert("Kotlin".padEnd(12, '-') == "Kotlin------")
assert("Kotlin".padStart(12, '.') == "......Kotlin")

val table = listOf(
    Triple("page1.html", 200, 1201),
    Triple("page2.html", 42, 8853),
    Triple("page3.html", 98, 3432),
    Triple("page4.html", 432, 900)
)

val output = table.map { data: Triple<String, Int, Int> ->
    data.first.padEnd(14, '.') +
            data.second.toString().padStart(5, '.') +
            data.third.toString().padStart(8)
}.joinToString(System.lineSeparator())

print(output)

assert(output == """
page1.html......200    1201
page2.html.......42    8853
page3.html.......98    3432
page4.html......432     900
""".trimIndent())

Written with Kotlin 1.7.20.