0
0
KotlinHow-ToBeginner · 3 min read

How to Use padStart and padEnd in Kotlin: Simple Guide

In Kotlin, padStart and padEnd add padding characters to the beginning or end of a string until it reaches a specified length. Use padStart(length, padChar) to add padding at the start, and padEnd(length, padChar) to add padding at the end.
📐

Syntax

The padStart and padEnd functions have this syntax:

  • fun String.padStart(length: Int, padChar: Char = ' '): String
  • fun String.padEnd(length: Int, padChar: Char = ' '): String

Explanation:

  • length: The total length of the resulting string after padding.
  • padChar: The character used for padding (default is space).
  • Returns a new string padded to the specified length.
kotlin
val original = "42"
val paddedStart = original.padStart(5, '0')
val paddedEnd = original.padEnd(5, '*')
💻

Example

This example shows how to use padStart and padEnd to add zeros at the start and stars at the end of a string.

kotlin
fun main() {
    val number = "42"
    val paddedStart = number.padStart(5, '0')
    val paddedEnd = number.padEnd(5, '*')
    println("Original: '$number'")
    println("padStart(5, '0'): '$paddedStart'")
    println("padEnd(5, '*'): '$paddedEnd'")
}
Output
Original: '42' padStart(5, '0'): '00042' padEnd(5, '*'): '42***'
⚠️

Common Pitfalls

Common mistakes include:

  • Using a length smaller than the original string length, which returns the original string unchanged.
  • Forgetting that padChar must be a single character.
  • Expecting padStart or padEnd to modify the original string (they return a new string).
kotlin
fun main() {
    val text = "hello"
    // Wrong: length less than original, no padding added
    println(text.padStart(3, '*')) // prints 'hello'

    // Wrong: padChar must be a Char, not a String
    // println(text.padEnd(8, "**")) // This will not compile

    // Right usage
    println(text.padEnd(8, '*')) // prints 'hello***'
}
Output
hello hello***
📊

Quick Reference

FunctionPurposeParametersReturns
padStart(length, padChar)Adds padding at the startlength: Int, padChar: Char (default ' ')New padded string
padEnd(length, padChar)Adds padding at the endlength: Int, padChar: Char (default ' ')New padded string

Key Takeaways

Use padStart to add characters at the beginning of a string to reach a desired length.
Use padEnd to add characters at the end of a string to reach a desired length.
If the specified length is less than or equal to the string length, the original string is returned unchanged.
The pad character must be a single character, not a string.
padStart and padEnd return new strings; they do not change the original string.