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 ".
- Pick the method. The lesson asks for
trim, which removes whitespace at both ends. - Store the result in a new
valnamedresult. It holdshello, with length 5, whilesstill has length 9.
val s = " hello "
val result = s.trim()
Gotchas
- Only the ends. Spaces in the middle stay:
" a b ".trimisa b. To collapse inner runs, usereplaceAll("\\s+", " "). - Use the result. Calling
s.trim()on its own line leavessas it was. - Parentheses are optional.
s.trimands.trim()both work. - Only whitespace.
" ".trimis the empty string. The methodisBlankchecks the same thing directly. - Not for other characters. To remove a known prefix, use
stripPrefix:"--x".stripPrefix("--")givesx.
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
trimandstripremove whitespace from both ends;stripLeadingandstripTrailingremove one end.- They return new strings and leave the original unchanged.
- Whitespace inside the string is never touched.
