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.
- Call
trim()ons. The two leading and the two trailing spaces are removed. - Store the returned string in
result. Because the call does not changes, 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(). Usetrim(). - Dropping the result.
s.trim()alone leavessas it was. - Expecting inner spaces to vanish. Only the ends are trimmed.
- Mixing up the directions.
trimStartworks on the beginning of the string,trimEndon its end.
Key takeaways
s.trim()removes leading and trailing whitespace;trimStart()andtrimEnd()do one side.- They return a new string and never modify the original.
- Whitespace inside the string stays.
trim('x')andtrim { condition }remove other characters from the ends.