Start learning free

LESSON 65 OF 414 · STRINGS I

String Strip and Trim in Scala: Removing Whitespace

Lesson Read the full explanation

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

s.strip()        // removes leading and trailing whitespace (Unicode-aware)
s.trim()         // removes leading and trailing ASCII whitespace
s.stripLeading() // removes only leading whitespace
s.stripTrailing()// removes only trailing whitespace

Here are some examples:

var s = "  hello  "
println(s.strip())         // "hello"
println(s.stripLeading())  // "hello  "
println(s.stripTrailing()) // "  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.trim() and assign the result to result.

STEP 1 OF 1
    Ctrl + Enter to check

    SCALA · STRINGS I

    String Strip in Scala, explained

    Removing whitespace at the ends

    Text from users, files and copy-and-paste often has stray spaces at the start or end. Scala strings have methods that remove them and return a new string:

    val s = "  hello  "
    
    println("[" + s.trim() + "]")          // [hello]
    println("[" + s.strip() + "]")         // [hello]
    println("[" + s.stripLeading() + "]")  // [hello  ]
    println("[" + s.stripTrailing() + "]") // [  hello]
    

    The brackets make the spaces visible. All four methods come from Java's String; strip, stripLeading and stripTrailing exist from Java 11 on, so they are available on Java 21. They don't change s, because strings are immutable.

    trim or strip?

    For ordinary spaces, tabs and newlines they behave the same:

    println("[" + "\t hi \n".trim + "]") // [hi]
    

    The difference is in unusual characters. trim removes every character whose code is at most the space character (code 32), which covers ordinary spaces and control characters. strip removes characters that Unicode defines as whitespace, such as the ideographic space  . For " hi ", strip() returns a string of length 2, while trim leaves all 4 characters. The non-breaking space   is removed by neither.

    The exercise, step by step

    The lesson gives you val s = " hello ".

    1. Pick the method. The lesson asks for trim, which removes whitespace at both ends.
    2. Store the result in a new val named result. It holds hello, with length 5, while s still has length 9.
    val s = "  hello  "
    
    val result = s.trim()
    

    Gotchas

    • Only the ends. Spaces in the middle stay: " a b ".trim is a b. To collapse inner runs, use replaceAll("\\s+", " ").
    • Use the result. Calling s.trim() on its own line leaves s as it was.
    • Parentheses are optional. s.trim and s.trim() both work.
    • Only whitespace. " ".trim is the empty string. The method isBlank checks the same thing directly.
    • Not for other characters. To remove a known prefix, use stripPrefix: "--x".stripPrefix("--") gives x.

    Why whitespace needs removing

    Two strings that look the same on screen can differ by an invisible space, and then == says they are different. Compare "hello" with "hello ": the second has length 6, so the two are not equal, even though a person would read them as the same word. Trimming input before comparing or storing it avoids this class of bug.

    The same applies to text read from a file or typed in a form, where a trailing newline or a stray space at either end is common. Call trim or strip once, as soon as the text arrives, and the rest of your code can assume clean values.

    A quick check of the effect is to print the length before and after. For the lesson's string, s.length is 9 and result.length is 5, the difference being the four spaces.

    Which one to choose

    For everyday text, any of them works, and the lesson's exercise uses trim. If your text might contain Unicode spaces from other writing systems, prefer strip, since it follows the Unicode definition of whitespace. If you only want to clean one side, for example a trailing newline, stripTrailing leaves the start of the string alone.

    Key takeaways

    • trim and strip remove whitespace from both ends; stripLeading and stripTrailing remove one end.
    • They return new strings and leave the original unchanged.
    • Whitespace inside the string is never touched.
    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free