How to Remove Whitespace from String in Kotlin
In Kotlin, you can remove whitespace from a string using
trim() to remove spaces at the start and end, or replace(" ", "") to remove all spaces inside the string. For more control, use filter with a condition to remove all whitespace characters.Syntax
trim(): Removes whitespace only from the start and end of the string.
replace(oldValue, newValue): Replaces all occurrences of oldValue with newValue in the string.
filter { condition }: Keeps only characters that meet the condition, useful to remove all whitespace characters.
kotlin
val original = " Hello World " val trimmed = original.trim() val noSpaces = original.replace(" ", "") val noWhitespace = original.filter { !it.isWhitespace() }
Example
This example shows how to remove whitespace from different parts of a string using trim(), replace(), and filter().
kotlin
fun main() {
val text = " Kotlin is fun! "
val trimmed = text.trim() // removes spaces at start and end
val noSpaces = text.replace(" ", "") // removes all spaces
val noWhitespace = text.filter { !it.isWhitespace() } // removes all whitespace characters
println("Original: '$text'")
println("Trimmed: '$trimmed'")
println("No spaces: '$noSpaces'")
println("No whitespace: '$noWhitespace'")
}Output
Original: ' Kotlin is fun! '
Trimmed: 'Kotlin is fun!'
No spaces: 'Kotlinisfun!'
No whitespace: 'Kotlinisfun!'
Common Pitfalls
Using trim() only removes spaces at the start and end, not inside the string. If you want to remove all spaces inside, you must use replace() or filter().
Replacing only space characters (' ') does not remove other whitespace like tabs or newlines. Use filter { !it.isWhitespace() } to remove all whitespace characters.
kotlin
fun main() {
val text = " Hello\tWorld \n "
// Wrong: only removes spaces, tabs and newlines remain
val replacedSpaces = text.replace(" ", "")
// Right: removes all whitespace characters
val removedWhitespace = text.filter { !it.isWhitespace() }
println("Replaced spaces: '$replacedSpaces'")
println("Removed all whitespace: '$removedWhitespace'")
}Output
Replaced spaces: 'Hello\tWorld\n'
Removed all whitespace: 'HelloWorld'
Quick Reference
| Function | Description | Example |
|---|---|---|
| trim() | Removes whitespace from start and end | " text ".trim() -> "text" |
| replace(" ", "") | Removes all space characters inside string | "a b c".replace(" ", "") -> "abc" |
| filter { !it.isWhitespace() } | Removes all whitespace characters (spaces, tabs, newlines) | "a\tb\nc".filter { !it.isWhitespace() } -> "abc" |
Key Takeaways
Use trim() to remove spaces only at the start and end of a string.
Use replace(" ", "") to remove all space characters inside the string.
Use filter { !it.isWhitespace() } to remove all types of whitespace characters.
Replacing spaces does not remove tabs or newlines; use filter for full whitespace removal.
Choose the method based on whether you want to remove whitespace only at edges or everywhere.