CodeBlanks Logo Icon CodeBlanks

trim and pad

Learn formatting with trim, padStart and padEnd.

trim: clean edge whitespace

trim removes leading and trailing whitespace from a string. Inner spaces are untouched. trimStart and trimEnd clean only one side.

val s = "  hello  "
println(s.trim())      // "hello"
println(s.trimStart()) // "hello  "
println(s.trimEnd())   // "  hello"

It is a good habit to trim user input before processing. Then stray spaces do not break comparisons. You can also trim specific chars: trim('*').

padStart and padEnd: pad to fixed length

padStart adds a given char to the front, padEnd to the back, until the string reaches the requested length.

val code = "5"
println(code.padStart(3, '0'))  // "005"
println(code.padEnd(3, '.'))    // "5.."

padStart is handy for fixed-width tables or sequence numbers. For example, month numbers become 01, 12. If you omit the second argument, a space is used by default.

Practice Pad the month to two digits

Pad the string "5" to 2 characters with padStart; fill the missing char with '0'. Print the result.

Starter code

Main.kt
fun main() {
    val month = "5"
    // Use padStart to make it 2 chars and print
}

Sample solution

Main.kt
val month = "5"
println(month.padStart(2, '0'))

Expected output

05

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does " hi ".trim() return?

  • " hi "
  • " hi"
  • "hi "
  • "hi" Correct answer

Explanation: trim removes leading and trailing spaces; not inner ones.

2 Fill in the blank: trim only the end

Question
val s = "  hi  "
val clean = s.____()
Answer
val s = "  hi  "
val clean = s.trimEnd()

Explanation: trimEnd removes only trailing spaces.

3 Match method to result

Term Meaning
trim() Edges cleaned
trimStart() Only front
padStart(3, '0') Pad zeros at front
padEnd(3, '.') Pad dots at end

4 Fill in the blank: pad with zeros

Question
val code = "5"
val padded = code.____(3, '0')
Answer
val code = "5"
val padded = code.padStart(3, '0')

Explanation: padStart(3, '0') puts two zeros in front, giving "005".

All lessons in Beginner