Print 0001 to 1000 in Kotlin with padding

Kotlin Mobile DevelopmentApps/Applications

In this example, we will see how to print 0001 to 1000 in Kotlin with padding. For this purpose, we will use a Kotlin library function called padStart().

padStart is a function which returns a charSequence. Its function definition looks like this −

fun CharSequence.padStart(
   length: Int,
   padChar: Char = ' '
): CharSequence

Example – Print 0001 to 1000 with padding

The following code prints 1 to 1000 with padding.

fun main(args: Array<String>) {
   (1..1000).forEach{println("$it".padStart(4, '0'))}
}

Output

On execution, it will print a sequence of 4-digit numbers starting from 0001 to 1000.

0001
0002
0003
0004
...
...
...
0996
0997
0998
0999
1000
raja
Updated on 01-Mar-2022 11:33:48

Advertisements