0
0
KotlinHow-ToBeginner · 3 min read

How to Trim String in Kotlin: Simple Guide with Examples

In Kotlin, you can trim whitespace from the start and end of a string using the trim() function. This function returns a new string without leading or trailing spaces. For example, " hello ".trim() results in "hello".
📐

Syntax

The basic syntax to trim a string in Kotlin is using the trim() function called on a string object.

  • string.trim(): Removes whitespace from both the start and end of the string.
  • string.trimStart(): Removes whitespace only from the start (left side).
  • string.trimEnd(): Removes whitespace only from the end (right side).
kotlin
val original = "  Kotlin  "
val trimmed = original.trim()
val trimmedStart = original.trimStart()
val trimmedEnd = original.trimEnd()
💻

Example

This example shows how to use trim(), trimStart(), and trimEnd() to remove spaces from a string.

kotlin
fun main() {
    val original = "  Hello Kotlin!  "
    println("Original: '" + original + "'")
    println("Trimmed: '" + original.trim() + "'")
    println("Trimmed Start: '" + original.trimStart() + "'")
    println("Trimmed End: '" + original.trimEnd() + "'")
}
Output
Original: ' Hello Kotlin! ' Trimmed: 'Hello Kotlin!' Trimmed Start: 'Hello Kotlin! ' Trimmed End: ' Hello Kotlin!'
⚠️

Common Pitfalls

One common mistake is expecting trim() to remove spaces inside the string, but it only removes spaces at the start and end. Also, trim() does not change the original string because strings are immutable in Kotlin; it returns a new trimmed string.

Another pitfall is forgetting to assign the trimmed result to a variable or use it directly, which means the original string remains unchanged.

kotlin
fun main() {
    val original = "  Kotlin  "
    original.trim() // This does not change original
    println("Original after trim(): '" + original + "'")

    val trimmed = original.trim() // Correct way
    println("Trimmed string: '" + trimmed + "'")
}
Output
Original after trim(): ' Kotlin ' Trimmed string: 'Kotlin'
📊

Quick Reference

FunctionDescription
trim()Removes whitespace from both start and end
trimStart()Removes whitespace from the start only
trimEnd()Removes whitespace from the end only

Key Takeaways

Use trim() to remove spaces from both ends of a string in Kotlin.
Strings are immutable; always use the returned trimmed string.
trimStart() and trimEnd() remove spaces only from one side.
trim() does not remove spaces inside the string.
Always assign or use the trimmed string result to see the effect.