Start learning free

LESSON 64 OF 348 · STRINGS I

String Strip in Kotlin: trim, trimStart and trimEnd

Lesson Read the full explanation

In Java, you can remove leading and trailing whitespace from a string using strip() (Java 11+) or trim():

s.trim()         // removes leading and trailing whitespace
s.trimStart()    // removes only leading whitespace
s.trimEnd()      // removes only trailing whitespace

Here are some examples:

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

These methods return a new String — the original is not modified.


Assignment
Follow the Coding Tutorial and strip whitespace from s!


Hint
Use s.strip() and assign the result to result.

STEP 1 OF 1
    Ctrl + Enter to check

    KOTLIN · STRINGS I

    String Strip in Kotlin, explained

    Removing extra whitespace

    Text from users, files and copy-and-paste often arrives with extra spaces, tabs or line breaks at its edges. Kotlin removes them with trim. Many languages call this operation strip, but in Kotlin the name is trim; there is no strip() on a Kotlin string, and calling it is a compile error (unresolved reference 'strip').

    val s = "  hello  "
    
    println(s.trim())      // hello
    println(s.trimStart()) // "hello  " (two spaces remain at the end)
    println(s.trimEnd())   // "  hello" (two spaces remain at the start)
    
    • trim() removes whitespace from both ends.
    • trimStart() removes it from the beginning only.
    • trimEnd() removes it from the end only.

    Whitespace here means any character that Kotlin's isWhitespace accepts: spaces, tabs and line breaks such as \n and \r among them. So "\n\t hi there \r\n".trim() gives hi there.

    What trim leaves alone

    Only the two ends are touched. Whitespace between words stays as it is:

    println("  a   b  ".trim()) // a   b
    

    The three spaces between a and b are still there. If you need to collapse those too, trim first and then replace each run of whitespace with a single space:

    val messy = "  too   many    spaces  "
    
    println(messy.trim().replace(Regex("\\s+"), " ")) // too many spaces
    

    The pattern \s+ matches one or more whitespace characters in a row, and every such run becomes one space. Splitting on the same pattern and joining the pieces with joinToString(" ") gives the same result. Trimming first matters: without it, the spaces at the ends would turn into one space each instead of disappearing.

    As with every string operation, the original is unchanged. Strings are immutable, so trim returns a new string:

    val s = "  hello  "
    val t = s.trim()
    
    println(s.length) // 9
    println(t.length) // 5
    

    The exercise

    The lesson provides s = " hello " and asks for a new val named result holding the string without its surrounding whitespace.

    1. Call trim() on s. The two leading and the two trailing spaces are removed.
    2. Store the returned string in result. Because the call does not change s, the result has to be captured to be used.
            val s = "  hello  "
    
            val result = s.trim()
    

    Now result is "hello" with a length of 5, while s still holds all 9 characters.

    Seeing the spaces

    Spaces are invisible in printed output, which makes trimming hard to check by eye. Print the string between visible marks, such as brackets, and the edges show up: println("[" + s.trimStart() + "]") prints [hello ], with the two trailing spaces visible before the closing bracket. Printing the length is another quick check.

    Trimming other characters

    The versions above remove whitespace. You can also name the characters to remove, or give a condition:

    println("xxhixx".trim('x'))                  // hi
    println("123abc456".trim { it.isDigit() })   // abc
    

    With a character, trim removes that character from both ends, however many times it repeats. With a lambda, it removes characters from each end as long as the lambda returns true. In both cases a character in the middle is never touched.

    Blank strings

    If a string holds only whitespace, trimming leaves the empty string. To test for that case directly, isBlank() is true for the empty string and for strings of whitespace only, so " ".isBlank() is true without you trimming first. isEmpty() is stricter: it is true only for a string of length 0.

    Where trim is used

    Trimming is the first step in cleaning input before you compare or convert it. Converting " 42 " with toInt() fails with a NumberFormatException, while " 42 ".trim().toInt() gives 42. In the same way, comparing user input to a fixed word is more reliable after trimming and lowercasing: " Hello ".trim().lowercase() is hello.

    Common mistakes

    • Calling strip(). Use trim().
    • Dropping the result. s.trim() alone leaves s as it was.
    • Expecting inner spaces to vanish. Only the ends are trimmed.
    • Mixing up the directions. trimStart works on the beginning of the string, trimEnd on its end.

    Key takeaways

    • s.trim() removes leading and trailing whitespace; trimStart() and trimEnd() do one side.
    • They return a new string and never modify the original.
    • Whitespace inside the string stays.
    • trim('x') and trim { condition } remove other characters from the ends.
    Keep going with KotlinAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free