How to pad a string in Kotlin
Sometimes, to keep up with the length of the string, we pad the string with some characters. In many communication protocols, keeping the standard length of the payload is vital. Kotlin makes it very easy to pad the string with any character and length. Let's see how to use it.
Getting ready
I'll be using IntelliJ IDEA for writing and running Kotlin code; you are free to use any IDE that can do the same task.
How to do it…
In this recipe, we will use the kotlin.stdlib
library of Kotlin. Specifically, we will be working with the padStart
and padEnd
functions. Let's now follow the given steps to understand how to use these functions:
- Let's see an example of the
padStart
function:
fun main(args: Array<String>) { val string="abcdef" val pad=string.padStart(10,'-') println(pad) }
This is the output:
----abcdef
- Next, we look at an example of
padEnd
:
val string="abcdef" val pad=string.padEnd(10,'-') println(pad)
Here's the output:
abcdef----
How it works…
The...