This article explores different ways to add padding to a string in Kotlin.

1. Using format() function

A common solution to left/right pad a string with spaces is using the format() function. For example,

Download Code

 
We can left-pad a numeric string with zeros by converting it to an integer and using the '0' flag, as shown below:

Download Code

2. Using padStart() and padEnd() function

Alternatively, we can use the padStart() library function to pad a string to the specified length, at the beginning, with the specified character or space. Similarly, the padEnd() library function can be used to pad a string to the specified length, at the end, with the specified character or space.

Download Code

That’s all about adding padding to a string in Kotlin.