Add padding to a string in Kotlin
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,
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
fun padLeft(s: String?, n: Int): String { return "%${n}s".format(s) } fun padRight(s: String?, n: Int): String { return "%-${n}s".format(s) } fun main() { val s = "ABC" val n = 5 println(padLeft(s, n)) // " ABC" println(padRight(s, n)) // "ABC " } |
We can left-pad a numeric string with zeros by converting it to an integer and using the '0' flag, as shown below:
|
1 2 3 4 5 6 7 8 9 |
fun padLeft(s: String, n: Int): String { return "%0${n}d".format(s.toInt()) } fun main() { val s = "1011101" val n = 16 println(padLeft(s, n)) // 0000000001011101 } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
fun padLeft(s: String, n: Int): String { return s.padStart(n, ' ') } fun padRight(s: String, n: Int): String { return s.padEnd(n, ' ') } fun main() { val s = "ABC" val n = 5 println(padLeft(s, n)) // "00ABC" println(padRight(s, n)) // "ABC00" } |
That’s all about adding padding to a string in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)